现在的位置: 首页 > 综合 > 正文

Net2.0 的新线程 ParameterizedThreadStart &BackgroundW

2012年10月15日 ⁄ 综合 ⁄ 共 1911字 ⁄ 字号 评论关闭

表示在 Thread 上执行的方法的委托方法,ThreadStart不能带参数,ParameterizedThreadStart是2.0中新增的,可以带参数(object类型的)

如果你想为一个线程传入变量你怎么办?

ThreadStart可不支持带参数的方法.所以你无法使用Thread来启动一个带参数的方法..

.Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库复制 .Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库保存

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的异步调用来实现

http://www.cnblogs.com/idior/articles/100666.html

现在在.Net2.0下提供了ParameterizedThreadStart 这么一个Delegate.它和ThreadStart 的不 同就在于可以拥有一个object类型的参数.也就是说你可以通过它来使用Thread类以启动一个线程并传入参数, 和Java很象了,不错的新功能.

.Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库复制 .Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库保存

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

}

******* static void ThreadMethod(object o)

{

string str = o as string;

Console.WriteLine(str);

}

}

}

还有一个新增的类BackgroundWorker,可以用于启动后台线程,并在后台计算结束后及时调用主线程的方法.一个常见的应用就是在 DataGrid中载入数据的时候.因为从数据库中载入DataSet比较耗时, 所以你可以使用BackgroundWorker来进行载入, 当 DataSet构造好后就立即绑定上DataGrid. 其实该功能同样可以通过Delegate的异步调用实现不过BackgroundWorker用 起来更方便一些.

.Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库复制 .Net2.0 的新线程 ParameterizedThreadStart BackgroundW - 医生 - 我的资料库保存

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

抱歉!评论已关闭.