Access ThreadStatic - Variable from outside of the thread

1k Views Asked by At

I have defined a Variable as ThreadStatic:

public static class MyApplicationContext {
    [ThreadStatic]
    public static bool Monitoring;
}

Now, I should set the variable Monitoring from the MainThread (which have started the new Thread):

this.syncThread = new Thread(this.InternalWork);
this.syncThread.SetApartmentState(ApartmentState.STA);
this.syncThread.Start();
// now, I should access MyApplicationContext.Monitoring of syncThread.

Is there a way to do this?

1

There are 1 best solutions below

0
On BEST ANSWER

My understanding is that ThreadStatic is always relative to the thread. You could get this info out if you instruct the thread to read is for you.

You could also make your static value an object, then have that thread add the reference to a central location to be monitored. You would still have the issues of making sure that changes to that object get periodically synced or set it to volatile.

By manually syncing or setting it to volatile, you remove a lot of the benefit of it being thread local. you also need to be careful if your ThreadStatic object is a data structure that could change. Your main thread attempting to read a changing data structure could throw exceptions, or even worse, return bad data.

I have no experience with ThreadStatic, so I'm going based off of my knowledge only.