Search code examples
c#multithreadingparameters

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?


Solution

  • 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.