Created
April 11, 2016 12:43
-
-
Save elitezhe/841429b78ecd700b33e5c32626ff3043 to your computer and use it in GitHub Desktop.
From http://www.cnblogs.com/yunfeifei/p/4106318.html 使用token和轮询方式在task执行过程中return,也可throw exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tokenSource = new CancellationTokenSource(); | |
var token = tokenSource.Token; | |
var task = Task.Factory.StartNew(() => | |
{ | |
for (var i = 0; i < 1000; i++) | |
{ | |
System.Threading.Thread.Sleep(1000); | |
if (token.IsCancellationRequested) | |
{ | |
Console.WriteLine("Abort mission success!"); | |
return; | |
} | |
} | |
}, token); | |
token.Register(() => | |
{ | |
Console.WriteLine("Canceled"); | |
}); | |
Console.WriteLine("Press enter to cancel task..."); | |
Console.ReadKey(); | |
tokenSource.Cancel(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment