Saturday, June 7, 2008

Passing Parameters to Threads in C#

A followup question that was asked on the "Waiting on a thread" post was how to pass parameters in the ThreadStart method.

This misunderstands what the Threadstart needs. It need the location of the function to pass control to when the thread is started. But you could create an object and use it to identify a method as the following code illustrates.

===Code Follows===

using System;
using System.Threading;
namespace ConsoleApplicationThread
{
public class ThreadClass
{
private int _Count = 0;
public ThreadClass(int count)
{
_Count = count;
}
public void ThreadMethod()
{
for (int i = 0; i < _Count; i++)
{
Console.WriteLine("ThreadClass.ThreadMethod {1}: {0}", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
}
}
}
public class MultiThreadStart
{
public static void Main()
{
Console.WriteLine("Main thread: Create multiple threads");
ThreadClass threadClass1 = new ThreadClass(10);
Thread thread1 = new Thread(new ThreadStart(threadClass1.ThreadMethod));
ThreadClass threadClass2 = new ThreadClass(20);
Thread thread2 = new Thread(new ThreadStart(threadClass2.ThreadMethod));
ThreadClass threadClass3 = new ThreadClass(30);
Thread thread3 = new Thread(new ThreadStart(threadClass3.ThreadMethod));
ThreadClass threadClass4 = new ThreadClass(40);
Thread thread4 = new Thread(new ThreadStart(threadClass4.ThreadMethod));
Console.WriteLine("Main thread: Start threads");
thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
Console.WriteLine("Main: Call Join() on each thread to wait for thread to end.");
thread1.Join();
thread2.Join();
thread3.Join();
thread4.Join();
Console.WriteLine("Main: All threads have ended");
Console.ReadLine();
}
}
}

No comments: