What is the usefulness of Task.Yield?

4

The documentation for this method says:

  

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

I read the source code for it and got lost even more! / p>

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

The class YieldAwaitable is described in this way: it provides a startable context to switch to a target environment ( provides an expected context for switching to a target environment ) .

I do not understand the actual use of it.

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

This question refers to the Task.Yield method and not to the yield keyword.

I did some translations on this question that may not be very good. Editions are welcome.  (1) I do not know if eagerly would replace 100% the word awaitable , so I added the spelling.

asked by anonymous 24.09.2017 / 12:26

1 answer

4

When using async/await , it is not guaranteed that the code will execute asynchronously, and in some cases, it may be desirable to always execute the method asynchronously, in this case you can use await Task.Yield() to force it to rotate 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 do not use await Task.Yield() this code would run synchronously until you get to the last line, where it would possibly run asynchronously, but since the call to Task.Yield was made it will force the code to run later , and when it is executed it can still happen to be synchronous, after all it will run in the same context that was started, in the case in the UI Thread     

03.10.2017 / 14:03