我在C#多线程程序中遇到了一个不良行为。我的一些静态成员正在其他线程中释放它们的值,而同一个声明类型的一些静态值不会丢失它们的值。C#静态变量跨线程访问
public class Context {
public Int32 ID { get; set; }
public String Name { get; set; }
public Context(Int32 NewID, String NewName){
this.ID = NewID;
this.Name = NewName;
}
}
public class Root {
public static Context MyContext;
public static Processor MyProcessor;
public Root(){
Root.MyContext = new Context(1,"Hal");
if(Root.MyContext.ID == null || Root.MyContext.ID != 1){
throw new Exception("Its bogus!") // Never gets thrown
}
if(Root.MyContext.Name == null || Root.MyContext.Name != "Hal"){
throw new Exception("It's VERY Bogus!"); // Never gets thrown
}
Root.MyProcessor = new MyProcessor();
Root.MyProcessor.Start();
}
}
public class Processor {
public Processor() {
}
public void Start(){
Thread T= new Thread (()=> {
if(Root.MyContext.Name == null || Root.MyContext.Name != "Hal"){
throw new Exception("Ive lost my value!"); // Never gets Thrown
}
if(Root.MyContext.ID == null){
throw new Exception("Ive lost my value!"); // Always gets thrown
}
});
}
}
这是一个线程突变问题,同时使用某些类型的静态成员?
通常,可变静态属性不能很好地与并发性兼容。您可能应该限制该状态的范围,或确保在并发访问时不会修改它。 – Servy
感谢您的回复,属性或字段成员?我根据目的在根类中使用了公共字段。 –
我的声明同样适用于属性和字段。它们以某种形式都是可变的公共状态。 – Servy