简体   繁体   English

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

[英]c# send parameters to anonymous thread function

I am using the next code to open a thread: 我正在使用下一个代码来打开一个线程:

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

I wish to pass an object to the thread function so I tried this approach: 我希望将一个对象传递给线程函数,所以我尝试了这种方法:

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

But this is not working, so you have any idea how to do it? 但这不起作用,所以你知道怎么做吗?

Define the object that you want to reference from your anonymous function ahead of your function, like this: 在函数之前定义要从匿名函数引用的对象,如下所示:

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

C# compiler will automatically capture the myObject object in the process of creating the anonymous function, making it available to use inside the function body. C#编译器将在创建匿名函数的过程中自动捕获myObject对象,使其可在函数体内使用。

The version you are using is a ThreadStart which takes no argument, we have to use a ParameterizedThreadStart which takes 1 argument (of type object ), so the corresponding lambda expression for that delegate would be something like this: 你正在使用的版本是一个不带参数的ThreadStart ,我们必须使用一个带有1个参数(类型为object )的ParameterizedThreadStart ,因此该委托的相应lambda表达式将是这样的:

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

Note that the Start method has an overload taking one argument allowing you to pass in the actual argument for the thread when running it. 请注意, Start方法有一个带有一个参数的重载,允许您在运行时传递线程的实际参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM