Skip to content

Instantly share code, notes, and snippets.

@elitezhe
Created April 11, 2016 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elitezhe/841429b78ecd700b33e5c32626ff3043 to your computer and use it in GitHub Desktop.
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
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