Access ThreadStatic - 来自线程外部的变量

时间:2014-06-06 15:26:15

标签: c# multithreading threadstatic

我已将Variable定义为ThreadStatic:

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

现在,我应该从MainThread设置变量Monitoring(已启动新线程):

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

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我的理解是ThreadStatic总是相对于线程。如果您指示线程为您阅读,则可以获取此信息。

您还可以将静态值设为对象,然后让该线程将引用添加到要监视的中心位置。您仍然会遇到以下问题:确保对该对象的更改定期同步或将其设置为volatile。

通过手动同步或将其设置为volatile,可以消除线程本地的许多好处。如果您的ThreadStatic对象是可以更改的数据结构,您还需要小心。尝试读取不断变化的数据结构的主线程可能会抛出异常,甚至会导致返回错误数据。

我没有使用ThreadStatic的经验,所以我的基础仅仅是基于我的知识。