http://www.albahari.com/threading/
给线程传递参数的几种方式:
- lambda表达式 ```csharp static void Main() { Thread t = new Thread ( () => Print (“Hello from t!”) ); t.Start(); }
static void Print (string message) { Console.WriteLine (message); }
2. 在start中给参数,(只能传递一个object)```csharpstatic void Main(){Thread t = new Thread (Print);t.Start ("Hello from t!");}static void Print (object messageObj){string message = (string) messageObj; // We need to cast hereConsole.WriteLine (message);}
防止主线程退出,后台线程以外结束的方法
There are two ways to accomplish this:
- If you’ve created the thread yourself, call
[Join](http://www.albahari.com/threading/#_Join_and_Sleep)on the thread. - If you’re on a pooled thread, use an event wait handle.
提升线程优先级
using (Process p = Process.GetCurrentProcess())p.PriorityClass = ProcessPriorityClass.High;
thread pool (Parallel Task Library)
task
task将thread pool加入线程池
static void Main() // The Task class is in System.Threading.Tasks{Task.Factory.StartNew (Go);}static void Go(){Console.WriteLine ("Hello from the thread pool!");}
Task.Factory.StartNew returns a Task object, which you can then use to monitor the task — for instance, you can wait for it to complete by calling its [Wait](http://www.albahari.com/threading/part5.aspx#_Waiting_on_Tasks) method.
Any unhandled exceptions are conveniently rethrown onto the host thread when you call a task’s [Wait method](http://www.albahari.com/threading/part5.aspx#_Waiting_on_Tasks). (If you don’t call Wait and instead abandon the task, an unhandled exception will shut down the process as with an ordinary thread.)
