c# - Create multiple threads and wait all of them to complete -
how create multiple threads , wait of them complete?
it depends version of .net framework using. .net 4.0 makes thread management whole lot easier using tasks:
class program {     static void main(string[] args)     {         task task1 = task.factory.startnew(() => dostuff());         task task2 = task.factory.startnew(() => dostuff());         task task3 = task.factory.startnew(() => dostuff());          task.waitall(task1, task2, task3);                 console.writeline("all threads complete");     }      static void dostuff()     {         //do stuff here     } }   in previous versions of .net use backgroundworker object, use threadpool.queueuserworkitem(), or create threads manually , use thread.join() wait them complete:
static void main(string[] args) {     thread t1 = new thread(dostuff);     t1.start();      thread t2 = new thread(dostuff);     t2.start();      thread t3 = new thread(dostuff);     t3.start();      t1.join();     t2.join();     t3.join();      console.writeline("all threads complete"); }      
Comments
Post a Comment