V
V
Vadim Nikiforov2021-07-16 18:08:17
.NET
Vadim Nikiforov, 2021-07-16 18:08:17

What will thread #1 do?

Let's imagine that this is part of some REST service that processes requests from the user. At some point, a request came from the user. A thread has been allocated to process a request from a user. Let's call it thread #1. What will happen to this thread during the execution of this method?

async Task<int> CalcAsync() 
{
    var res = await CalcInternalAsync(); 
    return res + 1; 
}

It turns out that the method CalcInternalAsync();is executed in another thread No. 2? What will thread #1 do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-07-16
@nikifovadim

The thread allocated to the task (Task) will reach CalcInternalAsync, then it will either be executed synchronously, if possible, or return to the thread pool for the duration of the asynchronous work.
When the asynchronous work ends, a thread (not necessarily the same) will be taken from the thread pool again, in which the continuation will be executed.
Here it is necessary to think considering the thread pool and the state machine into which async\await is converted. And you should think about asynchronous work as about work that is not performed by the processor, and therefore a thread is not needed for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question