您的位置:首页 > 其它

将方法作为参数,传递到线程中

2012-05-18 15:48 253 查看
打开线程传递参数是每个初学者都会碰到的问题,尤其传递一个方法进去比较复杂。.Net不支持指针,所以传递参数需要靠委托来实现。

1,首先定义一个委托和类,其中DoSomeThing是线程要执行的方法:

/// <summary>

/// 定义委托

/// </summary>

delegate void DelegateThreadFunction ();

/// <summary>

/// 线程类

/// </summary>

class DelegateThread

{

//委托对象

private DelegateThreadFunction threadFunction;

/// <summary>

/// 构造函数

/// </summary>

/// <param
name="threadFunction"></param>

public DelegateThread(DelegateThreadFunction threadFunction)

{

this.threadFunction
= threadFunction;

}

/// <summary>

/// 执行线程函数

/// </summary>

public void DoSomeThing()

{

if (threadFunction
!= null )

{

threadFunction();

}

}

}

2,定义要传入的方法,方法要和委托一致:

static void dosomething()

{

}

3,执行线程:

DelegateThread delegateThread
= new DelegateThread(dosomething);

Thread th
= new Thread( new ThreadStart (delegateThread.DoSomeThing));
[align=left] th.Start();[/align]

[align=left]转自:http://www.5x5f.com:8086/MyGroup/Discussion/Detail?GroupId=10002&DiscussionId=10471[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: