Google
WWW Yariv Hammer's Code Site

Thursday, October 20, 2005

Passing Parameter to Thread

Problem
Threads in .NET must start a functions which is void() (return no values and gets no parameters). But what if we want to pass parameters to the thread?

Solution
The parameter will be stored as a private member of the class:
-------------------------------

public class MyClass{
   public void DoSomething()
   {
      Thread t = new Thread(new ThreadStart(DoSomethingInThread));
      _parameterForThread = 5;
      t.Start();
   }
   private int _parameterForThread = -1;
   private void DoSomethingInThread()
   {
      _parameterForThread ++;
   }
}

------------------------------------------

Alternative Solution

This is not so elegant, because we need to store local data in a member (which does not necessary represent the class's state).
So to take the concept one step further, we can put all the relevant code in another class:
------------------------------------------

public class MyThread
{
   public MyThread(int parameterForThread )
   {
      _parameterForThread = parameterForThread ;
   }

   private int _parameterForThread = -1;
   public void DoSomethingInThread()
   {
      _parameterForThread ++;
   }
}

public class MyClass
{
   public void DoSomething()
   {
      MyThread mt = new MyThread(5);
      Thread t = new Thread(new ThreadStart(mt.DoSomethingInThread));
      t.Start();
   }
}

------------------------------------------

1 Comments:

At 8:08 AM, March 23, 2006, Anonymous Anonymous said...

Thanks Yariv,
You helped me to much.

 

Post a Comment

<< Home

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.