Thursday, 15 March 2012

c# - Is it possible to execute two async methods in parallel? -



c# - Is it possible to execute two async methods in parallel? -

if execute 2 tasks, can execute 2 tasks @ same time , wait until 2 tasks finished. code:

task<bool> tsk01 = task.run(()=> code; homecoming true); task<bool> tsk02 = task.run(()=> code; homecoming true); task.waitall(tsk01, tsk02); //next code

in case next code executed when tasks finished. application not blocked.

however if have code:

private async void button_click_2(object sender, routedeventargs e) { task<bool> tsk01 = mimetodoasync01(); task<bool> tsk02 = mimetodoasync02(); task.waitall(tsk01, tsk02); } private async task<bool> mimetodoasync02() { homecoming await taskex.run<bool>(() => { int64 resultado = 0; (int64 = 1; < 1000000000; i++) { resultado = resultado + 1; } homecoming true; }).configureawait(false); } private async task<bool> mimetodoasync01() { homecoming await taskex.run<bool>(() => { int64 resultado = 0; (int64 = 1; < 1000000000; i++) { resultado = resultado + 1; } homecoming true; }).configureawait(false); }

in sec alternative application blocked because waitall seems wait response tasks never happens.

why in first case application not blocked , in sec 1 is?

the method task.waitall block ui thread waits tasks homecoming before continuing.

the code examples gave creating task same (albeit written different ways). both homecoming task<bool>.

the difference function beingness run within both of lambda expressions. first illustration has "my code" reference , returns. sec illustration created 2 counters.

if "my code" defined differently the counters created in sec example, or if returning true in lambda expression, appearance of 1 waiting on other.

simply returning true end threads after created. where-as counter takes time compute (also depending on cpu speed).

if add together same counter function of first example, find both take same time, , task.waitallblocks ui. can utilize system.diagnositics.stopwatch class time it.

static void main(string[] args) { string test = console.readline(); system.diagnostics.stopwatch t = new system.diagnostics.stopwatch(); t.start(); task<bool> task1 = task.run<bool>(() => { homecoming true; }); task<bool> task2 = task.run<bool>(() => { homecoming true; }); task.waitall(task1, task2); t.stop(); console.writeline("elapsed time: " + t.elapsed); system.diagnostics.stopwatch t2 = new system.diagnostics.stopwatch(); t2.start(); task<bool> task3 = asyncmethod1(); task<bool> task4 = asyncmethod2(); task.waitall(task3, task4); t2.stop(); console.writeline("elapsed time: " + t2.elapsed); console.read(); }

c# asynchronous async-await

No comments:

Post a Comment