如果你想為一個線程傳入變數你怎麼辦?
ThreadStart可不支援帶參數的方法.所以你無法使用Thread來啟動一個帶參數的方法..
ThreadStart myThreadDelegate = new ThreadStart(ThreadMethod);
//public delegate void ThreadStart(); u can't pass a Parameter
Thread myThread = new Thread(myThreadDelegate);
myThread.Start(); //myThread.Start(o); Wrong!
不 過在.Net1.0下,你可以通過Delegate的非同步呼叫來實現.現在在.Net2.0下提供了ParameterizedThreadStart 這麼一個Delegate.它和ThreadStart 的不同就在於可以擁有一個object類型的參數.也就是說你可以通過它來使用Thread類以啟動一個線程並傳入參數, 和Java很象了,不錯的新功能.
using System;
using System.Threading;
namespace ParameterizedThreadStartTest
{
class Program
{
static void Main(string[] args)
{
ParameterizedThreadStart myParameterizedThreadDelegate = new ParameterizedThreadStart(ThreadMethod);
Thread myThread = new Thread(myParameterizedThreadDelegate);
object o = "hello";
myThread.Start(o);
}
private static void ThreadMethod(object o)
{
string str = o as string;
Console.WriteLine(str);
}
}
}
還有一個新增的類BackgroundWorker,可以用於啟動後台線程,並在後台計算結束後及時調用主線程的方法.
一個常見的應用就是在DataGrid中載入資料的時候.因為從資料庫中載入DataSet比較耗時, 所以你可以使用
BackgroundWorker來進行載入, 當DataSet構造好後就立即綁定上DataGrid. 其實該功能同樣可以通過Delegate的非同步呼叫實現不過BackgroundWorker用起來更方便一些.
//1. Instantiate a BackgroundWorker instance:
BackgroundWorker myDataWorker = new BackgroundWorker();
//2. Setup a DoWork delegate that does the work that you want to be done on the background thread.
myDataWorker.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs workerEventArgs)
{
workerEventArgs.Result = new XXXDAL().GetData();
}
);
//3. Setup a RunWorkerCompleted delegate that handles updating your UI with the data recieved on the background thread.
myDataWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs workerEventArgs)
{
DataSet data = (DataSet) workerEventArgs.Result;
this.dataGrid.DataSource = data;
}
);
//4.Run your worker by calling the RunWorkerAsync() method on your BackgroundWorker instance.
myDataWorker.RunWorkerAsync();
順便關注一下C#3.0
PDC上 Anders Hejlsberg將介紹未來的語言改進方向.
C#: Future Directions in Language Innovation from Anders Hejlsberg
Join Anders Hejlsberg, Distinguished Engineer and chief architect of the C# language, for an in-depth walkthrough of the new language features in C# 3.0. Understand how features like extension methods, lambda expressions, type inference, and anonymous types make it possible to create powerful APIs for expressing queries and interacting with objects, XML, and databases in a strongly typed, natural way.