threading

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Very simple question. I need to pass a parameter to a newly created thread.
How can I accomplish it. I'm sure it must be very easy - something like it
was in Win32 CreateThread had 1 4B parameter.
 
Very simple question. I need to pass a parameter to a newly created
thread.
How can I accomplish it. I'm sure it must be very easy - something like it
was in Win32 CreateThread had 1 4B parameter.

basically you have to create a helper class where you put all parameters as
fields and make the thread function a method of the class. this way you will
be able to use all parameters inside the thread func. remember to initialize
these parameters somehow before you start new thread.

Wiktor Zychla
 
Create a class for the thread and pass the parameter in the constructor of
the class:

public class MyThreadClass
{
private int param;

public void Run()
{
new Thread(new ThreadStart(DoSomethingImportant)).Start();
}

public void DoSomethingImportant()
{
param++;
}
}

public class TestApp
{
public static void Main()
{
MyThreadClass o = new MyThreadClass(100);
o.Run();
}
}

Michael
 
My preferred solution for this is to create a class that holds all the data
that the thread will need. Then, make an instance (non-static) method in
that class to encapsulate whatever work it is that you want to do in the
thread. Create an instance of your class in your main thread, initialize it
however you like, and then call Thread.Start on the method:

using System.Threading;
namespace ThreadExample {

class ThreadExample {
static void Main() {
myClass C = new myClass(12, "hello"); // construct and
initialize object to hold data for the thread
workerThread = new Thread(new
ThreadStart(c.myThreadStartMethod));
workerThread.IsBackground = true;
workerThread.Start();
}
}

class myClass {
private int SomeField;
private string SomeOtherField;
public void myClass(int i, string s) {
SomeField = i;
SomeOtherField = s;
}
public void myThreadStartMethod() {
// do lots of work involving SomeField and SomeOtherField
}
}
}
 
Back
Top