使Thread委托参数间接支持多参数

Thread类的构造函数有

1.Thread(ParameterizedThreadStart)

2.Thread(ThreadStart)

3.Thread(ParameterizedThreadStart, Int32)

4. Thread(ThreadStart, Int32)

这里要用到 Thread(ParameterizedThreadaStart) 构造函数。

ParameterizedThreadStart 参数是一个委托,该委托的原型返回void 类型,带object参数的。我们利用对象可以转换为数据。我们这里利用struct类型,把要传递的参数封装到struct里,分别传递到线程。

详情请看实例:

代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AboutThread2
{
    
struct Data 
    {
        
public string name;
        
public string sex;
        
public Data(string name,string sex)
        {
            
this.name = name;
            
this.sex = sex;
        }
    }

    
class Program
    {
        
public static void ThreadMainParamters(object o)
        {
            Data d 
= (Data)o;
            Console.WriteLine(
"My name is {0} and My Sex is {1}",d.name,d.sex);
        }

        
static void Main(string[] args)
        {
            Data d 
= new Data("Tao","Man");
            Thread t1 
= new Thread(ThreadMainParamters);
            t1.Start(d);
        }
    }
}
这样就间接将多个参数传到线程的构造函数中。
posted on 2010-08-31 17:17  晴天1848  阅读(519)  评论(0)    收藏  举报