What is the use of Task.Yield?

Asked

Viewed 793 times

6

The documentation of this method says:

Method Task.Yield() - adapted from English
Creates a task suitable which returns asynchronously to the current context when awaited.

I read the his source code and got lost even more!

public static YieldAwaitable Yield()
{
    return new YieldAwaitable();
}

The class YieldAwaitable is described this way: provides a context suitable to switch to a target environment (provides an awaitable context for switching into a target Environment).

I don’t understand the real use of it.

What does this function actually do? In what contexts would this method bring advantages and why?

This question concerns the method Task.Yield and not the keyword yield.

I did some translations on this question which may not be very good. Edits will be welcome. (1) I do not know if long-awaited would replace 100% of the word awaitable, so I brought the spelling.

1 answer

6


When using the async/await it is not guaranteed that the code will run asynchronously, and in some cases it may be desirable that the method is always run asynchronously, in this case you can use the await Task.Yield() to force it to run asynchronously.

private async void button_Click(object sender, EventArgs e)
{
    await Task.Yield(); // Faz com que o método retorne imediatamente

    var dados = ExecutaProcessoNaThreadDaInterface(); // Este código vai ser executado no futuro

    await ProcessaDadosAsync(data);
}

If you don’t use the await Task.Yield() this code would run synchronously until it reached the last line, where it would possibly run asynchronously, but as the call was made to Task.Yield it will force the code to be executed later, and when it is executed it may still happen to be synchronous, after all it will run in the same context that was started, in the case of UI Thread

Browser other questions tagged

You are not signed in. Login or sign up in order to post.