gpt4 book ai didi

c# - 任务报告 IsCompleted 但仍然阻止结果?

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

我在使用 .Net 4 类 System.Threading.Tasks 时遇到了一些策略行为。这个例子最好地证明了这一点:

var t = FunctionThatReturnsTaskAsync();
Trace.TraceInformation("Completed: " + t.IsCompleted);
return t.Result;

输出:“Completed: true”,但代码(几千次运行一次)然后永远阻塞在 t.Result。它既不返回也不抛出异常。怎么会这样!

返回的任务有时会很快完成,所以它可以在第二行完成也就不足为奇了。神秘之处在于为什么 t.Result 会阻塞。

最佳答案

异步方法自己返回任务,您可能有一个 Task< Task < T >>,内部任务由于“异步”而在“完成”之前返回,而外部任务<>认为它已完成。

请参阅 Stephen Toub 的博客文章:

http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx

http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx

请允许我引用一段相关的话:

To understand this effect, we need to remember how async methods operate. When you invoke an async method, it starts running synchronously. If the method doesn’t have any awaits in it, or if all of the awaits in the method are on awaitables that are already completed by the time they’re awaited, then the method will run entirely synchronously. However, when the method encounters the first await that yields, the async method returns. In the case of an async method that returns a Task or a Task, the method at this point returns the Task or Task that represents the async method’s execution, and the caller can use that task to wait synchronous (e.g. Wait()) or asynchronously (e.g. await, ContinueWith) for the method to asynchronously complete. In the case of a void method, though, no handle is handed back. Async void methods are thus often referred to as “fire and forget.”

关于c# - 任务报告 IsCompleted 但仍然阻止结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9309071/

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