c#向匿名线程函数发送参数

c#向匿名线程函数发送参数,c#,multithreading,parameters,C#,Multithreading,Parameters,我正在使用下一个代码打开一个线程: var thread = new Thread(() =>{ /*thread code*/ }); thread.Name = "Thread1"; thread.Start();` 我希望向线程函数传递一个对象,因此我尝试了以下方法: var thread = new Thread(() =>(myObject){ }); 但是这不起作用,所以你知道怎么做吗?在函数之前定义你想从匿名函数中引用的对象,如下所示:

我正在使用下一个代码打开一个线程:

var thread = new Thread(() =>{  
   /*thread code*/  
});  
thread.Name = "Thread1";  
thread.Start();`
我希望向线程函数传递一个对象,因此我尝试了以下方法:

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

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

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

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

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

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

var myObject=…// 您使用的版本是一个不带参数的
ThreadStart
,我们必须使用一个带1个参数的
ParameterizedThreadStart
(类型为
object
),因此该委托对应的lambda表达式如下所示:

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

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

您使用的版本是一个不带参数的
ThreadStart
,我们必须使用一个
参数化ThreadStart
,它包含一个参数(类型为
object
),因此该委托对应的lambda表达式如下所示:

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

请注意,
Start
方法有一个重载,其中包含一个参数,允许您在运行线程时传入该线程的实际参数。

()=>(){}
将不起作用。始终发布有效的代码。这是重复多次的,但更重要的是,您可能根本不需要线程。为什么要使用匿名方法使事情复杂化?你需要匿名方法的理由是什么?
()=>(){}
行不通。始终发布有效的代码。这是重复多次的,但更重要的是,您可能根本不需要线程。为什么要使用匿名方法使事情复杂化?你需要匿名方法的理由是什么?