Chinaunix首页 | 论坛 | 博客
  • 博客访问: 213298
  • 博文数量: 43
  • 博客积分: 3010
  • 博客等级: 中校
  • 技术积分: 660
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-11 11:49
文章分类

全部博文(43)

文章存档

2009年(39)

2008年(4)

我的朋友

分类: WINDOWS

2009-02-20 11:16:38

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

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();
阅读(373) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~