Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created April 25, 2012 08:42
Show Gist options
  • Save masaru-b-cl/2488268 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2488268 to your computer and use it in GitHub Desktop.
http://xin9le.blogspot.jp/2011/08/tpl-13.html を外からキャンセルするかどうか指定できるように
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var source = new CancellationTokenSource();
var token = source.Token;
var task = new Task(() =>
{
Console.WriteLine("Task : Begin");
foreach (var item in Enumerable.Range(0, 20))
{
Thread.Sleep(100);
token.ThrowIfCancellationRequested();
}
Console.WriteLine("Task : End");
});
task.Start();
Thread.Sleep(2000);
if (Console.ReadKey().Key == ConsoleKey.C)
{
Console.WriteLine("press cancel key");
source.Cancel();
}
try
{
task.Wait();
}
catch (AggregateException exception)
{
foreach (var inner in exception.InnerExceptions)
{
Console.WriteLine(inner.Message);
Console.WriteLine("Type : {0}", inner.GetType());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment