为什么 Task.Delay() 允许无限延迟? [英] Why does Task.Delay() allow an infinite delay?

查看:57
本文介绍了为什么 Task.Delay() 允许无限延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序冻结后,我找到了一个线程正在等待由 Task.Delay()(或 .NET 中的 TaskEx.Delay() 创建的任务的原因)4.0),它提供了一个计算出的 TimeSpan,由于一个错误,它有时被计算为 TimeSpanTotalMilliseconds 小于或等于 -1 且大于 -2(即 -10000 到 -19999 滴答之间的任何位置,含).

After my application froze I tracked down the cause to a thread waiting on a task created by Task.Delay() (or TaskEx.Delay() in .NET 4.0) for which it provided a computed TimeSpan that, due to a bug, was on occasion computed to a TimeSpan with a TotalMilliseconds of less than or equal to -1 and greater than -2 (i.e. anywhere between -10000 to -19999 ticks, inclusive).

看起来,当您传递 -2 毫秒或更低的负 TimeSpan 时,该方法会正确抛出 ArgumentOutOfRangeException,但是当您提供上述范围内的负 TimeSpan,它返回一个永远不会完成的 Task(通过将底层 System.Threading.Timer 设置为 dueTimecode> of -1 表示无穷大).这意味着在该任务上设置的任何延续将永远不会执行,并且任何发生在该 Task 上的 .Wait() 的糟糕线程都将永远被阻塞.

It appears that when you pass a negative TimeSpan that is -2 milliseconds or lower, the method correctly throws an ArgumentOutOfRangeException, but when you provide a negative TimeSpan from the range described above, it returns a Task that never completes (by setting the underlying System.Threading.Timer to a dueTime of -1 which denotes infinity). That means that any continuations set on that task will never execute, and any poor thread that happens to .Wait() on that Task will forever be blocked.

一个永远不会完成的Task有什么可能的用途?有人会期待这样的返回值吗?传递给 .Delay() 的任何负值(包括该特殊范围内的值)不应该抛出 ArgumentOutOfRangeException 吗?

What possible use can a Task that never completes have? Would anyone expect such a return value? Shouldn't any negative value passed to .Delay(), including values in that special range, throw an ArgumentOutOfRangeException?

推荐答案

超时.Infinite 或 -1 当您想无限期地等待需要不确定时间才能完成但最终会完成的长时间运行的任务时很有用.

Timeout.Infinite or -1 is useful when you want to wait indefinitely for a long-running task that will take an indeterminate amount of time to complete, but will eventually complete.

Win32 API 还使用常量 INFINITE = -1 来表示无限超时.

The Win32 API also uses a constant INFINITE = -1 for infinite timeouts.

您通常不想在 UI 线程中使用它,因为它可能会冻结 UI(这似乎是您的问题).但是在工作线程中有有效的用例 - 例如正在阻塞等待来自客户端的连接的服务器.

You wouldn't normally want to use it in a UI thread, as it could freeze the UI (which seems to be your problem). But there are valid use cases in a worker thread - e.g. a server that is blocking waiting for a connection from a client.

这篇关于为什么 Task.Delay() 允许无限延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆