c# - how to use this semaphore -


        list<int> cuis = persistencyservices.getlistofallcui();                      resourcelock = new semaphore(3, 5);           foreach (var cui in cuis)         {              thread workthread = new thread(new parameterizedthreadstart(worker));              workthread.start(cui);          }      }     public static void worker(object cui)     {          resourcelock.waitone();          debug.writeline(string.format("thread cui {0} in", cui));          thread.sleep(5000);         resourcelock.release();     } 

this code allows 3 threads in critical region @ time. problem because list contains more 1 million recors outofmemoryexception. think because if semaphor allows 3 threads enter critical region, 1 million threads created wait semaphore. how should change code prevent this? please

you don't want million threads. isn't clear doing, looks maybe parallel.foreach(...) want here, little work , plenty of sanity.

if want enforce 3 threads:

parallel.foreach(cuis, new paralleloptions { maxdegreeofparallelism = 3 },         worker); 

with:

public static void worker(int cui) {     debug.writeline(string.format("thread cui {0} in", cui));     thread.sleep(5000); } 

if want use semaphore, use waitone loop:

foreach (var cui in cuis) {     resourcelock.waitone();     thread workthread = new thread(new parameterizedthreadstart(worker));      workthread.start(cui);  } ... public static void worker(object cui) {     debug.writeline(string.format("thread cui {0} in", cui));      thread.sleep(5000);     resourcelock.release(); } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -