Paramatised method in new thread

Below is two sudo parts of code just to highlight my question, how do i passed a argument into a method when i want to call the method in a new thread. ? new paramatised thread in full netmf would do the trick, but i seem to be missing something in netmf.

Example 1 calling a method which will run in a new thread - no problem

Example 2 calling a method which will run in a new thread - problem the method needs to pass in a value which i cant seem todo in netmf.
this line would be the problem

Thread method_2_Thread = new Thread(method_2("passed in string"));

 // Example 1 normal thread call no parameters in called method
        void method_1()
        {
            // call method_2 in new thread
            Thread method_2_Thread = new Thread(method_2);
            method_2_Thread.Start(); 
        }

        void method_2()
        {
            //do some work here in this new thread
        }

        



        // Example 2 thread call with parameters in called method
        void method_1()
        {
            // call method_2 in new thread
            Thread method_2_Thread = new Thread(method_2("passed in string"));
            method_2_Thread.Start();
        }

        void method_2(string datain)
        {
            //do some work here in this new thread
        }

Make it a class variable :wink:



        private string _method_2_parameter = string.Empty;

        // Example 2 thread call with parameters in called method
        void method_1()
        {
            // call method_2 in new thread
            //Thread method_2_Thread = new Thread(method_2("passed in string"));

           _method_2_parameter = "passed in string";
           Thread method_2_Thread = new Thread(method_2);

            method_2_Thread.Start();
        }
 
        void method_2()
        {
            Debug.Print(_method_2_parameter);
            //do some work here in this new thread
        }


Just to give you other options, rather than execute the method directly, you can execute it inside a lambda passed to the Thread constructor.

Here is an example:


// Run Method1 on a new thread
new Thread(() => Method1()).Start();

// Run Method2 on a new thread with some arguments
// note the argument can actually be a variable outside of the lambda, the compiler will take 
// care of capturing the value.
new Thread(() => Method2("Passed in string")).Start();

Note: You can also split the creation and starting of the thread into separate steps.

1 Like

Iā€™d go for lambdas, global variables make me feel icky.

I agree. Using lambdas is more elegant and thread safe solution in this case.

thanks all,

lambdas do seem a more elegant solution, i didnt realise you could do this with lambdas gonna read up on these

thanks