c# - await vs Task.Wait - Deadlock? -
i don't quite understand difference between task.wait , await.
i have similar following functions in asp.net webapi service:
public class testcontroller : apicontroller { public static async task<string> foo() { await task.delay(1).configureawait(false); return ""; } public async static task<string> bar() { return await foo(); } public async static task<string> ros() { return await bar(); } // api/test public ienumerable<string> get() { task.waitall(enumerable.range(0, 10).select(x => ros()).toarray()); return new string[] { "value1", "value2" }; // never execute } } where get deadlock.
what cause this? why doesn't cause problem when use blocking wait rather await task.delay?
wait , await - while similar conceptually - different.
wait synchronously block until task completes. current thread literally blocked waiting task complete. general rule, should use "async way down"; is, don't block on async code. on blog, go details of how blocking in asynchronous code causes deadlock.
await asynchronously wait until task completes. means current method "paused" (its state captured) , method returns incomplete task caller. later, when await expression completes, remainder of method scheduled continuation.
you mentioned "cooperative block", assume mean task you're waiting on may execute on waiting thread. there situations can happen, it's optimization. there many situations can't happen, if task schedler, or if it's started or if it's non-code task (such in code example: wait cannot execute delay task inline because there's no code it).
you may find async / await intro helpful.
Comments
Post a Comment