c# - Thread blocked after await -


with code:

    static void main(string[] args)     {         console.writeline("main thread pre - " + getnativethreadid(system.threading.thread.currentthread));         task.run(() => asyncmethod()).wait();         console.writeline("main thread post - " + getnativethreadid(system.threading.thread.currentthread));         console.readkey();     }      static async task asyncmethod()     {         console.writeline("asyncmethod thread pre - " + getnativethreadid(system.threading.thread.currentthread));         await task.delay(4000).configureawait(false);         console.writeline("asyncmethod thread post - " + getnativethreadid(system.threading.thread.currentthread));     } 

the output is:

main thread pre - 8652 asyncmethod thread pre - 4764 asyncmethod thread post - 1768 main thread post - 8652 

using concurrency visualizer, can see during 4 second delay, thread 4764 stuck in synchronization. unblocked main thread on shutdown.

shouldn't thread 4764 returned threadpool once hits await? (that being said don't know inside concurrency visualizer)

shouldn't thread 4764 returned threadpool once hits await?

yes. , is.

(that being said don't know inside concurrency visualizer)

that's easy enough check. explicitly execute code in thread pool, , take @ thread looks in visualizer when it's not busy.

for example:

threadpool.queueuserworkitem(o =>     {         console.writeline("worker: " + getnativethreadid(system.threading.thread.currentthread));         thread.sleep(250);     }); 

(i added sleep shows more in visualizer having done :) ).

and when do, you'll see looks see. :)


when ran this, thread pool used same worker thread used original task. , can see thread pool worker thread sits in synchronization state while it's waiting more work.

which makes sense. @ abstract level, what's thread pool doing? whole point have threads exist. don't want threads out there working unless have work on. burn cpu time no reason. instead, wait on synchronization object.

when (like task) wants use one, queues work item, , thread pool signals thread it's got do. wakes thread, work, , blocks on synchronization object again, waiting else do.

if check call stack relevant threads, you'll see worker thread waiting on call waitforsingleobject(), , you'll see thread pool unblocks thread using releasesemaphore().

and shows synchronization state thread pool thread, saw.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -