【发布时间】:2017-06-28 17:50:07
【问题描述】:
什么时候来Task.IsCanceled = true;
代码:
var cts = new CancellationTokenSource();
string result = "";
cts.CancelAfter(10000);
try
{
Task t = Task.Run(() =>
{
using (var stream = new WebClient().OpenRead("http://www.rediffmail.com"))
{
result = "success!";
}
cts.Token.ThrowIfCancellationRequested();
}, cts.Token);
Stopwatch timer = new Stopwatch();
timer.Start();
while (timer.IsRunning)
{
if (timer.ElapsedMilliseconds <= 10000)
{
if (result != ""){
timer.Stop();
Console.WriteLine(result);
}
}
else
{
timer.Stop();
//cts.Cancel();
//cts.Token.ThrowIfCancellationRequested();
}
}
}
catch (OperationCanceledException)
{
Console.WriteLine(t.IsCanceled); // still its appear in false.
}
我的要求是 - 任务在 10 秒内未完成,需要取消任务。
所以我正在设置计时器并观看给定的秒数。它未完成意味着取消任务并显示错误消息。
【问题讨论】:
-
请附上Minimal, Complete, and Verifiable example。您显示的内容不完整。
-
取消token还不够,需要查看
method取消作业的代码 -
你能显示等待任务 t 的代码吗?正确地说,如果方法运行时间超过 20 秒,您想取消整个操作,是吗?
-
我将在哪里共享代码。这里无法分享代码。显示时间过长
标签: c# task-parallel-library task cancellationtokensource cancellation-token