c# - Improve the performance by multi-threading -


i'm trying improve winform application's performance make multi-threaded. class looks like:

public class mainclass {    list<dataitem> data; //thousands of dataitem, each independent     //and lot of non-thread-safe variables here,variable1 variable2 ...     public void go()    {       data.foreach(item => dealwithdataitem(item));    }     public void dealwithdataitem(dataitem item)    {       //costs long time here       step1(item);       step2(item); //and lot of stepn(item)    }     public void stepn(dataitem item)    {       //variable1 = blabla       //variable2 = blabla ..etc    } } 

i want use threadpool each dataitem.

data.foreach(item => threadpool.queueuserworkitem( s => dealwithdataitem(item) )); 

but many non-thread-safe variables! can't declare them in method, because it's shared between stepn methods. , it's quite hard make them thread-safe! doing wrong? solutions? thanks!

try using parallelenumerable.asparallel.

data.asparallel.foreach(dowork); 

it automatically create threads depending on amount of processors / cores. problem, it's included in framework 4.0. more info plinq. (and andras commented: framwork 3.5 available stand-alone reactive extensions (rx))

upd: 0xa3 said, refactoring code, making each item have it's own calc variables recommended. suggest extract calculation logics dataitem

or create special class "calculator", work, dataitem store data, , logics of calculations contained in calculator class.

data.asparallel.foreach(x=> new calculator().dowork(x)); 

where calculator class this

class calculator {    // variables here    void dowork(dataitem item)   {      step1(item);      step2(item);      // ...      // stepn(item);   } } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -