gpt4 book ai didi

c# - 当 Task.IsCancelled 设置为 true 时?

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:49 25 4
gpt4 key购买 nike

什么时候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 秒未完成,需要取消任务。

所以我正在设置计时器并监视给定的秒数。未完成意味着取消任务并显示错误消息。

最佳答案

您必须将 token 传递给您的方法。它应该检查 token 并尊重对 CancellationTokenSourceCancel() 的调用。

或者你自己做:

Task t = Task.Factory.StartNew(() =>
{
myResult = method(); // Request processing in parallel

cts.Token.ThrowIfCancellationRequested(); // React on cancellation
}, cts.Token);

一个完整的例子是这样的:

async Task Main()
{
var cts = new CancellationTokenSource();
var ct = cts.Token;
cts.CancelAfter(500);

Task t = null;
try
{
t = Task.Run(() => { Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); }, ct);
await t;
Console.WriteLine(t.IsCanceled);
}
catch (OperationCanceledException)
{
Console.WriteLine(t.IsCanceled);
}
}

输出是抛出一个OperationCanceledException,结果是

True

如果您删除 ct.ThrowIfCancellationRequested(); 部分,它将显示

False

编辑:

现在,您已经更新了问题,并对此发表了一些评论。首先,您将不再需要计时器,因为您正在使用 CancelAfter 方法。其次,您需要await 您的任务。所以这就是这样的:

string result = "";
cts.CancelAfter(10000);
Task t = null;
try
{
t = Task.Run(() =>
{
using (var stream = new WebClient().OpenRead("http://www.rediffmail.com"))
{
cts.Token.ThrowIfCancellationRequested();
result = "success!";
}
}, cts.Token);

await t;
}
catch (OperationCanceledException)
{
Console.WriteLine(t.IsCanceled);
}

这应该表明 t.IsCanceledtrue 但当然只有当 WebClient 的调用时间超过 10 秒时。

关于c# - 当 Task.IsCancelled 设置为 true 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com