Dan*_* K. 8 c# task-parallel-library
.NET 4.5.1:看来,我无法使用CancellationTokenSource内置超时取消在任务内运行的阻塞方法.
class Program
{
static void Main(string[] args)
{
var cts = new System.Threading.CancellationTokenSource();
System.Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};
MainAsync(args, cts.Token).Wait();
}
// MainAsync from http://stackoverflow.com/questions/9208921/async-on-main-method-of-console-app
static async Task MainAsync(string[] args, System.Threading.CancellationToken token)
{
Console.WriteLine("Starting MainAsync");
var cts = new System.Threading.CancellationTokenSource(3000);
var task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Starting task...");
var t = new System.Net.Sockets.TcpClient();
var buffer = new byte[t.ReceiveBufferSize];
t.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 1337));
Console.WriteLine("Recieving...");
t.Client.Receive(buffer);
Console.WriteLine("Finished Recieving...");
return true;
}, cts.Token);
var success = await task;
Console.WriteLine("Did the task complete succesfuly?", success);
}
}
Run Code Online (Sandbox Code Playgroud)
以上Short,Self Contained,Correct示例的输出(我希望它是正确的)是:
Starting MainAsync
Starting task...
Recieving...
Run Code Online (Sandbox Code Playgroud)
为什么任务没有取消,没有抛出异常?
正如我在博客上所说的那样,"你一直在CancellationToken那里使用它.我不认为这意味着你认为它意味着什么."
特别是,CancellationToken传递给StartNew只会取消委托的启动.如果您希望委托本身支持取消,那么委托本身将必须遵守CancellationToken.