1

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • If you want it to be write-only from the main thread, then you can pass a lambda to `Start` and have the thread modify the variable itself. But my guess is that you don't really need `ThreadStatic`. What you need a regular static variable with some class that has a dictionary with thread ids as keys and a locker object to synchronize access properly. – Agent_L Jun 06 '14 at 16:39
  • 1
    From the [ThreadStatic documentation](http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(v=vs.110).aspx): "A static field marked with ThreadStaticAttribute is not shared between threads." I can't say whether it's *possible* to do what you're asking, but it's almost certainly a bad idea. It strikes me as akin to using reflection to diddle `private` fields of a class instance. You probably should revisit your design and come up with something more reasonable that doesn't require you to do silly things. – Jim Mischel Jun 06 '14 at 16:55

1 Answers1

1

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.

Bengie
  • 1,035
  • 5
  • 10