dinesh707
dinesh707

Reputation: 12582

How to pass variables into a Thread in C#?

In my code im running a thread. What I need to do now is to pass a variable to "SayHello" method. Since it is calling in a separate thread my variables are not visible for the thread.

ThreadStart ts = new ThreadStart(SayHello);
mThread = new Thread(ts);
mThread.Start();

Im new to C# and please let me know how to do this.

Upvotes: 1

Views: 1645

Answers (2)

DFSFOT
DFSFOT

Reputation: 542

You can only pass through an object.

//Declaring the Thread    
Thread T1;

// Calling the Thread
object[] threadPass = { String1, String2, Int1 };
T1 = new thread(Threadvoid);
T1.Start(threadPass);

// Thread Void
void Threadvoid(object passedObject)
{
    //Take the variables back out of the object
    object[] ThreadPass = passedObject as object[];
    string String1 = ThreadPass[0].ToString();
    string String2 = ThreadPass[1].ToString();
    int Int1 = Convert.ToInt32(ThreadPass[2]);
}

Upvotes: 1

BlackCath
BlackCath

Reputation: 826

this is how I pass values. First, your parameter must be a object, so you need to cast in your method. Your method must return void, if you need to return values, you can do it in many ways, volatile variables, or thread communication, etc. Then:

string sParameters = "This is my parameter";
Thread thrProcess = new Thread(MyMethod);
thrProcess.IsBackgroud = true;   // only if needed
thrProcess.Start(sParameters);   // string derives from object

And in your method:

void MyMethod(object param)
{
    string sParameterValue = (string)param;
// Now you can work with sParameterValue
}

If you need to pass more than one variable, then create a class and assign your values to properties, and cast in your method, but there are other ways to archive this. Hope this helps. If you need more info, chech this link: Threading in C#

Good luck!

Upvotes: 1

Related Questions