将方法作为参数,传递到线程中
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]
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]
相关文章推荐
- GO中url.Values作为参数传递的两种解析方法
- 传递参数到线程的n个方法
- C# 线程传递参数推荐方法
- OC 对象作为方法的参数连续传递
- 启动线程时传递参数的方法
- Kotlin语言学习之将函数作为参数传递,使用双冒号::引用其他方法
- 对象作为方法的参数进行连续传递一
- axios向后台传递数组作为参数的方法
- Java 把对象作为参数传到一个方法里,这个是值传递还是引用传递, 为什么结果这么怪?
- c++中关于数组作为函数参数并传递数组元素个数的几种有效方法的讨论
- 对象作为方法的参数进行连续传递二
- 如何解决JavaScript中UUID作为方法参数在方法中无法传递而数字却正常传递的问题
- 对象作为方法的参数连续的传递
- C语言中将二维数组作为参数传递给函数的方法
- java向线程中传递参数的方法
- 传递参数到线程的n个方法
- 匿名方法---将代码块作为参数传递给委托
- 数组作为函数参数的传递方法
- 对象作为方法的参数进行连续传递三
- C#往线程里传递参数的方法小结