Pass Variables to a New Thread in C#

When you create a new thread in .net 1.1, you cannot pass any parameters to the ThreadStart delegate, which makes passing startup variables difficult. This recipe shows you an easy workaround.

Since the ThreadStart delegate doesn’t accept parameters, you need to set the parameters somewhere before you create the new thread. What we’ll do is create a small class to store the variables, and then create a function in the class to pass into ThreadStart.

class myObject
public string myvariable;

public void RunThread()
// use myvariable here

You should really use properties instead of a public variable, but this makes the code sample simpler. The method that you pass into ThreadStart must be void, and accept no parameters.

Here’s the sample code for creating the object, passing in a variable, and then using the object to create the new thread:

myObject m = new myObject();
m.myvariable = "test data that the thread will need";

// Create the new thread, using the function
// from the object we created

Thread t = new Thread(new ThreadStart(m.RunThread));
t.IsBackground = true;
t.Name = "UpdateBookmarkThread";

Now when the thread is started, it will have access to the variables stored in it’s own object instance. This technique is very useful if you need to open multiple threads, passing in different information to each.

The Conversation

Follow the reactions below and share your own thoughts.

7 Responses to “Pass Variables to a New Thread in C#”

  1. August 17, 2009 at 9:08 am, Anonymous said:

    yeah hello there..

    i have a problem dude..

    i’m having a thread which uploads a file and i calculating uploading status with in the thread which i’d like store in the global variables like session..

    my page refreshes at 2 seconds and reports back the uploading status..

    but i’m not able to catch that value in session…

    i ve tried u r way but again it returns if u have any bright ideas..

    then plx helpp…


  2. December 30, 2009 at 5:33 am, Anonymous said:

    Its strange, it is not getting……… please help me too on same.


  3. March 13, 2011 at 3:44 am, Notnecessary said:

    better do nothing than doing it.


  4. October 31, 2011 at 9:20 am, irrildbiceRip said:

    юля вконтакте http vkontakte news vk hd odnokl накрутка подписчиков вконтакте

    vk r ru
    vk dj скачать бесплатно
    vk golosa бесплатно
    yamaha vk
    http vkontakte ru foto


  5. November 26, 2011 at 2:49 pm, 7897809 said:

    Вдруг князь Ипполит поднялся и, знаками рук останавливая всех и просяприсесть, заговорил:- Ah! aujourd’hui on m’a racontй une anecdote moscovite, charmante: il


  6. January 25, 2012 at 8:05 am, poolleyAgek said:

    Всем привет!!


  7. May 30, 2012 at 3:32 pm, Evan said:

    Or upgrade your core to 2.0+ and call parameterizedthreadstart. Who targets .NET 1.1 these days anyway. I sincerely hope this is a really old post.


Leave a Reply