i intend run 2 tasks in parallel , wait both of them finish. here 2 tasks:
private async function tempworker1() task = 1 5000 if mod 100 = 0 console.writeline("from 1:{0}", i) end if next end function private async function tempworker2() task = 1 5000 if mod 100 = 0 console.writeline("from 2:{0}", i) end if next end function i run them as:
dim task1 task = tempworker1() dim task2 task = tempworker2() await task.whenall(task1, task2).configureawait(false) however, don't think tasks running in parallel.
here output get:
from 1:1000 1:2000 1:3000 1:4000 1:5000 2:1000 2:2000 2:3000 2:4000 2:5000 as can see, finishes task 1 , task 2 finishes. have increased iterations near positive infinity , checked - same story.
how run these 2 tasks in parallel?
marking method async means method allowed await on 1 or many asynchronous operations within method. keyword doesn't magically turn method asynchronous one. in fact, because don't await on within tempworker1 , tempworker2 methods methods in effect synchronous.
supporting documentation: link
an async method typically contains 1 or more occurrences of await operator, absence of await expressions doesn’t cause compiler error. if async method doesn’t use await operator mark suspension point, method executes synchronous method does, despite async modifier. compiler issues warning such methods.
because marking method async keyword without awaiting on within method not useful, compiler should have given following warning:
warning async method lacks 'await' operators , run synchronously. consider using 'await' operator await non-blocking api calls, or 'await task.run(...)' cpu-bound work on background thread.
in case, if want parallelize work, need start them in separate threads. , 1 way this, calling task.run. notice that, using task.run, there no longer need 2 methods have async keyword set on them, or remain function matter.
so can accomplish goal this:
private sub tempworker1() = 1 5000 if mod 100 = 0 console.writeline("from 1:{0}", i) end if next end sub private sub tempworker2() = 1 5000 if mod 100 = 0 console.writeline("from 2:{0}", i) end if next end sub and execute work in parallel this:
dim task1 task = task.run(addressof tempworker1) dim task2 task = task.run(addressof tempworker2) await task.whenall(task1, task2).configureawait(false) note: if coded properly, may not observe parallel execution expect if work performed each tempworkerx method not great. if execution of full method able execute within single time slice or quantum, may still appear though 1 method executes , completes before other starts. make sure tempworkerx methods perform enough work parallelization become noticeable.
Comments
Post a Comment