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

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

问题描述

应用程序冻结后,我将原因归结为一个线程,等待一个由 Task.Delay()(或 TaskEx.Delay)创建的任务(。在.NET 4.0中),为此它提供了一个计算的 TimeSpan ,由于错误,有时会被计算为 TimeSpan TotalMilliseconds 小于或等于 -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).

传递一个负的 TimeSpan 小于或等于 -2 毫秒的时间,该方法将正确抛出一个 ArgumentOutOfRangeException ,但是当您从上述范围提供负的TimeSpan时,它将返回一个任务,该任务永远不会完成(通过设置基础的 System.Threading.Timer dueTime 为-1(表示无穷大)。这意味着在该任务上设置的任何延续都将永远不会执行,并且在该 Task .Wait()的任何不良线程。 $ c>将永远被阻止。

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?

推荐答案

或-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天全站免登陆