c#将参数发送给匿名线程函数

时间:2013-12-01 13:11:08

标签: c# multithreading parameters

我正在使用下一个代码打开一个帖子:

var thread = new Thread(() =>{  
   /*thread code*/  
});  
thread.Name = "Thread1";  
thread.Start();`

我希望将一个对象传递给线程函数,所以我尝试了这种方法:

var thread = new Thread(() =>(myObject){  
}); 

但这不起作用,所以你知道怎么做吗?

2 个答案:

答案 0 :(得分:2)

在函数之前定义要从匿名函数引用的对象,如下所示:

var myObject = ... // <<== Define object here
var thread = new Thread(() => {
    Console.WriteLine("My object: {0}", myObject);
    /*thread code*/  
});  
thread.Name = "Thread1";  
thread.Start();

C#编译器将在创建匿名函数的过程中自动捕获myObject对象,使其可在函数体内使用。

答案 1 :(得分:1)

您使用的版本是ThreadStart,它不带参数,我们必须使用带有1个参数(类型为ParameterizedThreadStart)的object,因此相应的lambda表达式为该代表将是这样的:

var thread = new Thread((arg) =>{  
    //use the arg here ...
});
//then run the thread like this
thread.Start(myObject);

请注意,Start方法有一个重载,它带有一个参数,允许您在运行时传递线程的实际参数。