multithreading - C# Task ConfigureAwait -
multithreading - C# Task ConfigureAwait -
thought getting handle on configureawait, tried experiment.
my understanding configureawait(false) create difference if there synchronization context.
asp, wpf, etc. should have context, console apps , service apps should not.
to see how works made web api app , included next method:
// api/values/5 public async task<string> (int id) { var syncctx = synchronizationcontext.current; int startthreadid = thread.currentthread.managedthreadid; await task.delay(timespan.fromseconds(3)).configureawait(true); int endthreadid = thread.currentthread.managedthreadid; homecoming "start thread id: " + startthreadid.tostring() + ": end thread id: " + endthreadid.tostring(); } my prediction no configureawait or configureawait set true, should see same thread id before , after await.
my first few tests showed true set above.
later runs of code started , ended on different thread ids regardless of configureawait.
i added syncctx convince myself have context.
the 1 caveat have read if task has completed, won't guaranteed same id. case here? if so, why case?
have set naive or flawed test? if so, proper test?
i started downwards path in console/service app , realized not getting same thread id. adding configureawait(false) recommended in "best practice" write ups have seen. since see how things work, tried testing thread ids. seeing them differ led me through number of searches resulted in above code.
doing configureawait(true) (or leaving off, default value) not create run on same thread. tells synchronizationcontext.current post or send rest of continueation. how post or send runs code not defined.
windowsformssynchronizationcontext , dispatchersynchronizationcontext (winforms , wpf's contexts) both set continuation on queue of messages processed message pump (the ui thread).
on other hand, aspnetsynchronizationcontext (which running under) sets state info (like setting httpcontext.current old value), queues work on next available thread pool thread. there no "message pump" asp.net, of work on thread pool, there no point in trying same thread out of thread pool @ later time, thread may been destroyed time continuation happens.
the times saw same id before , after got lucky , same thread got pulled out of thread pool before , after continuation.
i highly recommend read msdn mag article "it's synchronizationcontext", goes in detail explaining how synchronizationcontext works , goes in little detail 4 types of contexts built in .net.
c# multithreading asynchronous
Comments
Post a Comment