简体   繁体   中英

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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