Main Site Documentation

How can you pass parameters to new Thread?


#1

The obvious way was to do:



But no ParameterizedThreadStart exist in netmf.

Suggestion?

#2

Static global variables? Variable capture also works (I think), when using lambdas.


#3

I like to put my threads into a class:

public class MyThread
    {
        private Thread _thread = null;
        private int p1;
        private string p2;

        public MyThread(int parameter1, string parameter2)
        {
            p1 = parameter1;
            p2 = parameter2;
        }

        public void Start()
        {
            _thread = new Thread(_Run);
            _thread.Start();
        }

        private void _Run()
        {
            // we are now in the thread, and have access 
            // to parameters from constructor


        }
    }

To use the class:

MyThread t = new MyThread(1, "test");
t.Start();

#4

as Mike said use a separate class and to make it easier for your programming add the word delegate in you class name, using Mikes example I would call it:


public class MyThreadDelegate
{
.....

}

cheers,
Jay.


#5

Use of the word “delegate” in the class name is a style choice not a requirement. ;D


#6

@ Mike - What about thread.abort() and thread.join() ?

I changed it to be:



But it didn't help something about cannot derive...
In that case I think we should make _thread as public so we can do
t._thread.stop()

#7

Since objects created with ‘new’ are created on the heap and no thread marshalling is required on these objects (unless you create a Handle tied to its owning thread), you can just reference the class scope objects directly from your new thread.

Be careful with concurrent access to these objects from different threads if they bear some state. If no appropriate locking is applied they can become corrupted.

See Mike’s comments inside “_Run”.


#8

I usually add abort and join methods to the class. Habot’s mention of locking is very important.


#9

check out the thread example from the samples installed on your computer… they should cover most of your questions:


C:\Users\xxxx\Documents\Microsoft .NET Micro Framework 4.3\Samples\Threading

replace the xxxx with the user name of your login… or browse to the folder under my Documents folder…

cheers,