c# - "async await " how to understand it -
the code :
static void main(string[] args) { test(); console.writeline("main thread id :{0}", thread.currentthread.managedthreadid); console.read(); } static async void test() { console.writeline("before wait current thread id:{0}", thread.currentthread.managedthreadid); await getname(); console.writeline("after wait current thread id:{0}", thread.currentthread.managedthreadid); } static async task getname() { await task.run(() => { console.writeline("current thread id :{0}", thread.currentthread.managedthreadid); console.writeline("in antoher thread....."); }); }
the result :
before wait current thread id:9 current thread id :10 in antoher thread..... main thread id :9 after wait current thread id:10 or after wait current thread id:11
i dont kown why "main thread id" running fast "after wait current thread id". , why has 3 threadid.
well, can trace happens.
for main thread:
- method
test
called before wait
printed out- a new task queued on threadpool, ,
test
returnsmain
up point, definite synchronous sequence. remainder not deterministic, because in theory, either rest of main
or threadpool task
can execute first - in fact, can (in theory) interleave, main thread id
being printed out in between of current thread id
, in thread
.
however, after wait
printed after in thread
.
you can see there's at least 2 threads involved - shouldn't surprising when use task.run
. third 1 come from? well, await
doesn't magic. there's no instruction magic in il. schedule continuation on task
you're awaiting, rest of method. , since there's no synchronization context marshal continuation on, continuation queued thread pool again - taking thread. however, in theory, continuation may allowed run synchronously on original thread (that is, 1 used in task.run
), although in case assume it's reuse of original thread, rather synchronous continuation. can entirely sure of 1 thing - never run on main thread - not unless explicitly setup synchronization context , handle marshalled tasks on main thread instead of using console.read
final blocking operation.
Comments
Post a Comment