Is this a good candidate for using async await in this C# .NET code? -


i have collection of objects. before save these objects, need grab reference data database. need few calls db each object. these methods can happen in order / not dependent upon each other.

can use async / await make these db operations happen @ same time ?

parallel.foreach(animals,     animal => {         animal.owner = getanimalowner(ownerid);         animal.favouritefood = getfavouritefood(foodid);          database.store(animal);     }); 

that's pseudo code explains i'm trying do. candidate async / await ?

if want execute 2 operations in parallel, don't need async-await. can use old tpl methods, parallel.invoke():

parallel.foreach(animals,     animal => {         parallel.invoke(             () => animal.owner = getanimalowner(ownerid),             () => animal.favouritefood = getfavouritefood(foodid));          database.store(animal);     }); 

keep in mind there no guarantee improve performance, depending on db , connection it.

in general, async-await makes sense in 2 cases:

  1. you want offload long-running code ui thread.
  2. you want use less threads improve performance or scalability.

it seems me #1 not case. if you're in case #2, should rewrite database methods asynchronous ones (depending on db library, may not possible).

if that, similar scott chamberlain suggested (but not using parallel.foreach()):

var tasks = animals.select(     async animal => {         var getownertask = getanimalownerasync(ownerid);         var getfavouritefoodtask = getfavouritefoodasync(foodid);          animal.owner = await getownertask;         animal.favouritefood = await getfavouritefoodtask;          await database.storeasync(animal);     });  await task.whenall(tasks); 

this execute bigger degree of parallelism parallel.foreach() (because that's limited thread pool), again, may not improve performance. if wanted limit degree of parallelism, add semaphoreslim or use tpl dataflow instead.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -