Threads with signatures different of ThreadStart

  • Thread starter Thread starter Fernando Rodríguez
  • Start date Start date
F

Fernando Rodríguez

Hi,

ThreadStart doesn't take any parameters. How can I create threads that take
parameters? O:-)

Thanks
 
A common technique is to create a class wich holds the parameters and then
let the thread work on that.

ie;

<code>

public class WorkerClass
{
public int startInt;
public string startString;
Thread workerThread;

public WorkerClass(int StartInt, string StartString)
{
this.startInt = StartInt;
this.startString = StartString;
}

public void Start()
{
workerThread = new Thread(new ThreadStart(this.Process);
workerThread.Start();
}

public void Process()
{
// use variables;
}
}

class StarterApp
{
static void Main()
{
WorkerClass work = new WorkerClass(1, "fortytwo");
work.Start();
}
}

</code>
 
Hi Fernando.,
the easiest thing you can do is something like the following:

class Main{
[STAThread]
static void Main(string[] args)
{
ThreadStartWrap ts = new ThreadStartWrap("some value that might not be a
string ...");
Thread t = new Thread(new System.Threading.ThreadStart(ts.StartPoint));
t.Start();
}
}

class ThreadStartWrap
{
object _myParam;
public ThreadStartWrap(object myParam)
{
this._myParam = myParam;
}
public void StartPoint()
{
//use input param here
Console.WriteLine(_myParam);
}
}

It depends on the case whether you need something more complicated - like
putting in some eventhandling or some thread synch logic, but that's the
general idea.

Cheers,
Branimir
 
If you want a threadpool thread you could do this:

private delegate void MyDelegate(string text);
private void button6_Click(object sender, System.EventArgs e)
{
// Fire a simple method on the thread pool with no args and void return
using a system defined delegate.
new System.Windows.Forms.MethodInvoker(DoThis).BeginInvoke(null, null);

// Fire a custom delegate on the thread pool with user defined delegate.
new MyDelegate(DoThat).BeginInvoke("Delegates are fun.", null, null);
}

private void DoThis()
{
Console.WriteLine("Did this.");
Console.WriteLine("Is Thread Pool?:" +
Thread.CurrentThread.IsThreadPoolThread);
}

private void DoThat(string text)
{
// Also call EndInvoke.
Console.WriteLine("Did that:"+text);
Console.WriteLine("Is Thread Pool?:" +
Thread.CurrentThread.IsThreadPoolThread);
}
 
Back
Top