c# - Running async methods in parallel -
i've got async method, getexpensivething()
, performs expensive i/o work. how using it:
// serial execution public async task<list<thing>> getthings() { var first = await getexpensivething(); var second = await getexpensivething(); return new list<thing>() { first, second }; }
but since it's expensive method, want execute these calls in in parallel. have thought moving awaits have solved this:
// serial execution public async task<list<thing>> getthings() { var first = getexpensivething(); var second = getexpensivething(); return new list<thing>() { await first, await second }; }
that didn't work, wrapped them in tasks , works:
// parallel execution public async task<list<thing>> getthings() { var first = task.run(() => { return getexpensivething(); }); var second = task.run(() => { return getexpensivething(); }); return new list<thing>() { first.result, second.result }; }
i tried playing around awaits , async in , around tasks, got confusing , had no luck.
is there better run async methods in parallel, or tasks approach?
is there better run async methods in parallel, or tasks approach?
yes, "best" approach utilize task.whenall
method. however, second approach should have ran in parallel. have created .net fiddle, should shed light. second approach should running in parallel. fiddle proves this!
consider following:
public task<thing[]> getthingsasync() { var first = getexpensivethingasync(); var second = getexpensivethingasync(); return task.whenall(first, second); }
note
it preferred use "async" suffix, instead of getthings
, getexpensivething
- should have getthingsasync
, getexpensivethingasync
respectively - source.
Comments
Post a Comment