Raskolnikov
Raskolnikov

Reputation: 3999

When async-await change thread?

When async-await change thread?

In test2() method time required to finish method is even longer then in test1()

    [Route("api/[controller]")]
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        await MainAsync();
        return new ObjectResult(null);
    }

    static async Task MainAsync()
    {
        Console.WriteLine("Main Async: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        await test1();
        //await test2();
        // . . .more code
    }

    private static async Task test1()
    {
        Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        await Task.Delay(1);
        Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
    }

    private static async Task test2()
    {
        Console.WriteLine("thisIsAsyncStart: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        System.Threading.Thread.Sleep(5000);
        await Task.FromResult(0);
        Console.WriteLine("thisIsAsyncEnd: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
    }

Upvotes: 2

Views: 2338

Answers (1)

Servy
Servy

Reputation: 203827

test1 awaits Task.Delay(1), which isn't going to be completed at the time it goes to await it, meaning the rest of test1 needs to be scheduled as a continuation.

For test2 you're awaiting Task.FromResult, which will always return an already completed Task. When you await an already completed task the method can just keep running on the current thread, without needing to schedule a continuation.

Upvotes: 9

Related Questions