Task.Delay(0) not asynchronous

后端 未结 1 2032
遥遥无期
遥遥无期 2021-02-13 15:57

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

    async void setTimeout(dynamic callback, int timeout)
    {
             


        
1条回答
  •  我在风中等你
    2021-02-13 16:16

    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();
    }
    

    0 讨论(0)
提交回复
热议问题