c# - Thread safe with Linq and Tasks on a Collection -


given code so

public class customcollectionclass : collection<customdata> {} public class customdata {     string name;     bool finished;     string result; }  public async task doworkinparallel(customcollectionclass collection) {     // collection can retrieved db, may not exist.     if (collection == null)     {         collection = new customcollectionclass();         foreach (var data in mydata)          {              collection.add(new customdata()             {                 name = data.name;             });         }     }      // part doesn't feel safe. not sure here.     var processtasks = mydata.select(o =>          this.doworkonitemincollection(collection.single(d => d.name = o.name))).toarray();      await task.whenall(processtasks);      await savemodifedcollection(collection); }  public async task doworkonitemincollection(customdata data) {     await doabunchofworkelsewhere();     // doesn't feel safe either. lock here?     data.finished = true;     data.result = "parallel"; } 

as noted in couple comments inline, doesn't feel safe me above, i'm not sure. have collection of elements i'd assign unique element each parallel task , have tasks able modify single element of collection based on work done. end result being, wanted save collection after individual, different elements have been modified in parallel. if isn't safe way it, how best go this?

your code right way this, assuming starting doabunchofworkelsewhere() multiple times safe.

you don't need worry linq query, because doesn't run in parallel. invoke doworkonitemincollection() multiple times. invocations may work in parallel (or not, depending on synchronization context , implementation of doabunchofworkelsewhere()), code showed safe.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -