I have the following code (yes, I could be simulating JavaScript setTimeout
api)
async void setTimeout(dynamic callback, int timeout)
{
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();
}