Task.Delay(0)不是异步的

编程入门 行业动态 更新时间:2024-10-25 16:26:29
本文介绍了Task.Delay(0)不是异步的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码(是的,我可能正在模拟JavaScript setTimeout api)

async void setTimeout(dynamic callback, int timeout) { await Task.Delay(timeout); callback(); }

对于timeout > 0来说,setTimeout异步工作,其中控件返回到await上的callee,并且在任务异步运行后调用callback. BUT ,当timeout == 0时,该功能以同步方式运行(代码始终在同一线程中经过等待行,而无需上下文切换).在进一步挖掘中,事实证明Task.Delay被实现为以这种方式运行( Task.Yield()与Task.Delay(0))

想知道是否有一种方法可以使Task.Delay(0)异步,或者是否可以在timeout为0时使我的setTimeout函数异步? (以便模仿JavaScript setTimeout 功能.)我看到了有关使用Task.FromResult(true)或Task.WhenAll的讨论,但它们似乎没有用.

实际上,我可以使用Task.Delay(1)代替Task.Delay(0),但是看起来不自然.

解决方案

Task.Delay(0)不能异步运行的原因是因为async-await状态机显式检查任务是否已完成以及任务是否已完成.

您可以尝试使用任务. Yield(),这将强制该方法立即返回并在当前SynchornizationContext上恢复该方法的其余部分.例如:

async void setTimeout(dynamic callback, int timeout) { if(timeout > 0) { await Task.Delay(timeout); } else { await Task.Yield(); } callback(); }

I have the following code (yes, I could be simulating JavaScript setTimeout api)

async void setTimeout(dynamic callback, int timeout) { await Task.Delay(timeout); callback(); }

It looks like for timeout > 0, the setTimeout works asynchronously wherein the control is returned back to the callee on await and callback is invoked after the task runs asynchronously. BUT when timeout == 0, the function behaves in a synchronous manner (code always run past the await line in the same thread without a context switch). On further digging, it turns out that Task.Delay is implemented to behave this way (Task.Yield() versus Task.Delay(0))

Wondering if there is a way to make Task.Delay(0) asynchronous or an alternate solution to make my setTimeout function asynchronous when timeout is 0? (so that I could mimic JavaScript setTimeout functionality) I see discussions on using Task.FromResult(true) or Task.WhenAll, but they don't seem to work.

Indeed I can use Task.Delay(1) instead of Task.Delay(0) but it does not look organic.

解决方案

The reason Task.Delay(0) does not run asynchronously is because the async-await state machine explicitly checks whether the task is completed and if it is, it runs synchronously.

You can try using Task.Yield(), which will force the method to return immediately and resume the rest of the method on the current SynchornizationContext. eg:

async void setTimeout(dynamic callback, int timeout) { if(timeout > 0) { await Task.Delay(timeout); } else { await Task.Yield(); } callback(); }

更多推荐

Task.Delay(0)不是异步的

本文发布于:2023-11-08 16:19:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Task   Delay

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!