public int DoWork() { using (ManualResetEvent resetEvent = new ManualResetEvent(false)) { ManualResetEvent[] handles = new ManualResetEvent[2]; for (int i = 0; i < 2; i++) { handles[i] = new ManualResetEvent(false); } ThreadPool.QueueUserWorkItem( new WaitCallback((x) => { Thread.CurrentThread.Name = "2"; Work.SomeLongTask(); handles[(int)ThreadPooler.counter].Set(); Interlocked.Increment(ref ThreadPooler.counter); })); ThreadPool.QueueUserWorkItem( new WaitCallback((x) => { Thread.CurrentThread.Name = "3"; Work.AnotherLongTask(); handles[(int)ThreadPooler.counter].Set(); Interlocked.Increment(ref ThreadPooler.counter); })); WaitHandle.WaitAll(handles); Work.SomeLongTask(); Console.WriteLine("counter = {0}", counter); } return(1); }
public int DoWork() { Task <String>[] taskArray = { Task <String> .Factory.StartNew(() => { Thread.CurrentThread.Name = "7"; String res = Work.SomeLongTask(new object()); return(res); }), Task <String> .Factory.StartNew(() => { Thread.CurrentThread.Name = "8"; String res = Work.AnotherLongTask(new object()); return(res); }) }; String results = ""; for (int i = 0; i < taskArray.Length; i++) { results += taskArray[i].Result; Console.WriteLine("res {0}", taskArray[i].Result); } Console.WriteLine("results :{0}", results); Work.AnotherLongTask(); return(1); }
public int DoWork() { Parallel.For(0, 3, (index) => { if (index == 0) { try { Thread.CurrentThread.Name = "4"; } catch { Console.WriteLine("thread cant be renamed probably main thread, {0}", Thread.CurrentThread.Name); } finally { Work.SomeLongTask(); } } else if (index == 1) { try { Thread.CurrentThread.Name = "5"; } catch { Console.WriteLine("thread cant be renamed, {0}", Thread.CurrentThread.Name); } finally { Work.AnotherLongTask(); } } else { try { Thread.CurrentThread.Name = "6"; } catch { Console.WriteLine("thread cant be renamed, {0}", Thread.CurrentThread.Name); } finally { Work.AnotherLongTask(); } } }); return(1); }