Friday, 15 August 2014

Multithreading and assigning array to each thread in c# -



Multithreading and assigning array to each thread in c# -

i writing code sending email multiple users. have replace content of mail service according user info. no of users high, want multiple threads sends mail service prepare no of users. want create thread , assign each thread array specifies users' info. how can it?

int noofthread = noofusers / 5000; private ilist<thread> threadlist = new list<thread>(); for(int i=0; i<noofthread; i++) { thread thread = new thread(functiontocall); thread.isbackground = true; thread.name = threadsendmail + i; threadlist.add(thread); thread.start(); }

how can assign array each thread , pass function functiontocall()?

my suggestion not utilize thread @ that's obsolete tpl (task parallel library) in place, code needs this:

parallel.foreach(userlist, user => { // email send action here, can modify details per user here } );

or

parallel.for(0, noofthread, user => { // email send action here, can modify details per user here } );

benefits immense:

it cpu core optimization , assign based on availability. runtime optimization based on environment / logical cores etc

you not need decide upon number of threads create static formula above, not lead optimization , 1 size fit all

int noofthread = noofusers / 5000;

even if want apply such formula bring in environment.processorcount vary per processor count in system, still not runtime optimization , availability.

parallel api internally utilize threadpool, much improve such scenarios, since thread expensive resource , want them reused pool, not create , destroy. each thread has stack allocation of 1 mb default , not want memory allocate , destroy , not reuse via pool

c# multithreading

No comments:

Post a Comment