Sobes.tech
Junior — Middle

If a method run asynchronously executes synchronously, does the thread return to the thread pool after its completion?

sobes.tech AI

Answer from AI

If an asynchronous method in C# executes synchronously (for example, it does not contain await or completes the task immediately), then the thread on which it runs is not blocked and is not held longer than necessary.

However, if the method is started with async and returns a Task, but contains synchronous code inside, then the thread executing it does not necessarily return to the thread pool until the method completes.

When using Task.Run to run synchronous code in the thread pool, the thread will be busy until the work is finished and only then return to the pool.

Thus:

  • If the method is asynchronous but runs synchronously on the current thread (for example, the UI thread), the thread does not go into the thread pool.
  • If the method is started with Task.Run, the thread from the pool is busy until completion.

Example:

async Task ExampleAsync()
{
    // Synchronous code
    Thread.Sleep(1000); // blocks the current thread
}

// Call
await ExampleAsync();

Here, the thread will be busy during the Sleep.

If you use Task.Run:

await Task.Run(() => Thread.Sleep(1000));

The thread from the pool will be busy for 1 second, then returned to the pool.