標籤:c# thread delegate
1. 利用Thread start啟動線程
ThreadStart表示執行線程的方法
ThreadStart(delegate(){})
public static void testThread() { int Max_Thread_Count = 10; long currentThreadCount = 0; for(var i = 0;i < 100;i ++) { var ii = i; while(true) { if (Interlocked.Read(ref currentThreadCount) < Max_Thread_Count) break; Thread.Sleep(1000); } Interlocked.Increment(ref currentThreadCount); new Thread(new ThreadStart(delegate() { Thread.Sleep(1000); Console.WriteLine("Current position is " + ii); Thread.Sleep(1000); Interlocked.Decrement(ref currentThreadCount); })).Start(); } while (true) { Console.WriteLine("Running thread count " + currentThreadCount); if (Interlocked.Read(ref currentThreadCount) == 0) break; Thread.Sleep(1000); } }
ThreadStart(方法名)
public static void testThread() { int Max_Thread_Count = 10; long currentThreadCount = 0; for(var i = 0;i < 100;i ++) { var ii = i; while(true) { if (Interlocked.Read(ref currentThreadCount) < Max_Thread_Count) break; Thread.Sleep(1000); } Interlocked.Increment(ref currentThreadCount); new Thread(new ThreadStart(DoWork)).Start(); //new Thread(new ThreadStart(Work.DoWork)).Start(); Interlocked.Decrement(ref currentThreadCount); } while (true) { Console.WriteLine("Running thread count " + currentThreadCount); if (Interlocked.Read(ref currentThreadCount) == 0) break; Thread.Sleep(1000); } } public static void DoWork() { Console.WriteLine("Static thread procedure."); } class Work { public static void DoWork() { Console.WriteLine("Static thread procedure."); } public int Data; public void DoMoreWork() { Console.WriteLine("Instance thread procedure. Data={0}", Data); } }
2. 利用ThreadPool QueueUserWorkItem執行多線程
public static void testThread() { int Max_Thread_Count = 10; var semaphore = new Semaphore(Max_Thread_Count, Max_Thread_Count); for(var i = 0;i < 100;i ++) { var ii = i; ThreadPool.QueueUserWorkItem( (state0) => { semaphore.WaitOne(); Thread.Sleep(2000); Console.WriteLine("Process " + ii); semaphore.Release(); } ); } }
http://stackoverflow.com/questions/3334178/limit-threads-count
3. 兩種方法的主要區別
這個裡面的分析比較好: http://stackoverflow.com/questions/6192898/thread-start-versus-threadpool-queueuserworkitem
Starting a new thread can be a very expensive operation. The thread pool reuses threads and thus amortizes the cost. Unless you need a dedicated thread, the thread pool is the recommended way to go. By using a dedicated thread you have more control over thread specific attributes such as priority, culture and so forth. Also, you should not do long running tasks on the thread pool as it will force the pool to spawn additional threads.
In addition to the options you mention .NET 4 offers some great abstractions for concurrency. Check out the Task and Parallel classes as well as all the new PLINQ methods.
ThreadPool可以重複利用線程,因而更省成本。Thread start直接用起來更方便點。
C#中多線程使用Thead和ThreadPool比較