Skip to content

Instantly share code, notes, and snippets.

@Aimeast
Last active August 29, 2015 14:03
Show Gist options
  • Save Aimeast/81212d65a596c537eb83 to your computer and use it in GitHub Desktop.
Save Aimeast/81212d65a596c537eb83 to your computer and use it in GitHub Desktop.
Test CancellationToken
static void Main()
{
var source = new CancellationTokenSource();
var task1 = Task.Factory.StartNew(() =>
{
Console.WriteLine("run task1");
Task.Delay(2000).Wait();
Console.WriteLine("after delay task1");
source.Token.ThrowIfCancellationRequested();
Console.WriteLine("no exec task1");
}, source.Token); // pass cancellation token or not
var task2 = task1.ContinueWith(t =>
{
Console.WriteLine("run task2");
}, TaskContinuationOptions.OnlyOnCanceled); // mark here as OnlyOnCanceled or NotOnCanceled
Task.Delay(100).Wait();
source.Cancel();
try
{
task1.Wait();
}
catch (AggregateException e)
{
Console.WriteLine("Exception messages:");
foreach (var ie in e.InnerExceptions)
Console.WriteLine(" {0}: {1}", ie.GetType().Name, ie.Message);
Console.WriteLine("\nTask status: {0}", task1.Status);
}
Task.Delay(-1).Wait();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment