views:

135

answers:

4

I am running a thread in C#. I have web form. I declared public string attribute in my web form. (e.g. string myVal) Then I called thread and assign value into myVal. It assign values in it. But when I exit from thread code, myVal become null.

Is there anyway to keep myVal value.

public string myVal;

protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread myThread = new System.Threading.Thread(this.getVal);
            myThread.SetApartmentState(System.Threading.ApartmentState.STA);
            myThread.Start();
            myThread.Join();

//I am not able to get myVal string over here.

}

private void getVal()
{
myVal = "I can easily get myVal over here.";
}
+1  A: 

Do you reference myVal further in your code or are you just inspecting it with the debugger and checking the value after you are done with it? If so maybe the garbage collector has already gotten to it.

Matt
Yes I need myVal after thread code.
Syed Tayyab Ali
+1  A: 

Test Case failure: I copy-pasted your code in a new ASP.NET Project and added, after the myThread.Join() :

Label1.Text = myVal;

And the label does show your string.

Henk Holterman
+1  A: 

In general what you seem to be doing is trying to keep a value around after the thread it was created on has exited.

I would recommend using an App Domain(MSDN). In short, an all threads sit inside an AppDomain (for more info visit the link) and you already have one by the nature of the program.

So what you would do in your situation is:

To "save" the data: AppDomain.CurrentDomain.SetData("val", myVal);

To retrieve the data: AppDomain.CurrentDomain.GetData("val");

Hope that helps

Josh
+1  A: 

My guess is you are getting "System.InvalidOperationException: Cross-thread operation not valid" in the getVal method. You could put a try catch around it to verify that an exception is being thrown. I would suggest using a BackgroundWorker or other form of callback.

SwDevMan81
I tried this with a WinForms project and its seems to work just like Henk Holterman said
SwDevMan81