您的位置:首页 > 其它

.Net2.0 的线程 ParameterizedThreadStart &BackgroundWorker

2009-11-22 17:39 260 查看
如果你想为一个线程传入变量你怎么办?

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();

原文地址:/article/4606574.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: