gpt4 book ai didi

c# - 如果我在任务中延迟,为什么 ContinueWith 会执行

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

我对任务并行库中的 ContinueWith 似乎做了什么感到有点困惑。

我的理解是,在任务完成之前不应调用它。如果我处于 while true 循环中,则根本不应该调用它。

        DateTime t = DateTime.Now.AddSeconds(10);
Task.Factory.StartNew(async () =>
{
while (true)
{
if (t < DateTime.Now) //after 10s throw
{
throw new Exception(); //I expect it to run the continuation here
}

Console.WriteLine("looped");
await Task.Delay(new TimeSpan(0, 0, 1));
}
}
).ContinueWith(ct => Console.WriteLine("Continued with: {0}",ct.Result.Status)) ;

我希望在抛出异常之前,以下代码不会运行 ContinueWith 方法,但事实并非如此。相反,我得到以下输出:

looped
Continued with: WaitingForActivation
looped
looped
looped
looped
looped
looped
looped
looped
looped

为什么当我遇到第一个延迟时它会调用 ContinueWith?

最佳答案

Task.Factory.StartNew 返回的任务是 Task<Task>因为你的 lambda 返回一个 Task那个 lambda 在线程池上运行。该 lambda 的结果包装在 Task<T> 中。并放入其 Result属性(property)。

所以你需要调用Unwrap或者更好地使用 Task.Run .

关于c# - 如果我在任务中延迟,为什么 ContinueWith 会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261274/

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