0

However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

Actually, just doing an await can do that. Once your async method hits an await, the method is blocked but the thread returns to the thread pool. When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method.

Source

I've just tested that in a console program:

async Task foo()
{
    int y = 0;
    while (y<5) y++;
}

async Task testAsync()
{
    int i = 0;
    while (i < 100)
    {
        Console.WriteLine("Async 1 before: " + i++);

    }
    await foo();

    while (i < 105)
    {
        i++;
        Console.WriteLine("Async 1 after: " + i);
    }
}

Calling await foo() doesn't cause the thread testAsync was running on to return to thread pool, testAsync just runs line by line on the same thread from start to end. What's am I missing here?

Community
  • 1
  • 1
user4205580
  • 564
  • 5
  • 25
  • 1
    `foo` is running synchronously, there should be a compiler warning stating that. – Ivan Stoev Nov 14 '15 at 17:26
  • 2
    If you are testing in a Console app, then the main thread is not a ThreadPool thread, so it will not *return* to the ThreadPool. How did you test that? – Arghya C Nov 14 '15 at 17:27
  • @ArghyaC I've started that using `await Task.Run(() => testAsync())`, which takes a WorkerThread from the thread pool and executes `testAsync` on it (you can check it using threads window in the debugger). – user4205580 Nov 14 '15 at 17:36

2 Answers2

8

What's am I missing here?

You are missing compiler warnings

Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

The method foo isn't really asynchronous as there are no await calls in it.
Try adding await Task.Delay in there.

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61