2014-01-09 29 views
0

我试图运行在一个单独的线程的方法,但是当我尝试初始化新的线程我得到这个错误:线程的方法

A field initializer cannot reference the non-static field, method, or property Form1.update()

更新方法:

public void update() 
{ 
    XmlDocument doc = new XmlDocument(); 
    status s = new status(); 
    doc.LoadXml(s.getStatus("12345")); 

    char[] xmlChar = { 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; 
    int[] lightStatus = new int[9]; 
    int[] doorStatus = new int[5]; 
    int[] fanStatus = new int[5]; 
    int[] windowStatus = new int[5]; 
    for (int i = 1; i < 9; i++) 
    { 
     XmlNode lights = doc.SelectSingleNode("All/Lights/status/" + xmlChar[i] + "/text()"); 
     lightStatus[i] = Convert.ToInt16(lights.Value); 
    } 

    for (int i = 1; i < 5; i++) 
    { 
     XmlNode fans = doc.SelectSingleNode("All/Fans/status/" + xmlChar[i] + "/text()"); 
     XmlNode doors = doc.SelectSingleNode("All/Doors/status/" + xmlChar[i] + "/text()"); 
     XmlNode windows = doc.SelectSingleNode("All/Windows/status/" + xmlChar[i] + "/text()"); 
     fanStatus[i] = Convert.ToInt16(fans.Value); 
     doorStatus[i] = Convert.ToInt16(doors.Value); 
     windowStatus[i] = Convert.ToInt16(windows.Value); 
    } 
    u1.update(lightStatus); 
    u2.update(fanStatus); 
} 

我在初始化得到一个错误:

System.Threading.Thread updateThread = new System.Threading.Thread(update); 
+2

http://stackoverflow.com/questions/12659551/threading-problems-in-c-sharp-a-field-initializer-cannot-reference-the-non-stat 这可能会帮助你。 – Nil23

+0

或者这个:http://stackoverflow.com/questions/2642978/how-to-call-the-method-in-thread-with-aruguments-and-return-some-value –

回答

1

你在哪里把你的decalartion为主题? 你可以尝试把它放在你的构造函数上吗?

像这样:

/* *********** */ 
/* CONSTRUCTOR */ 
/* *********** */ 

public MyConstructor() 
{ 
    // ..... 

    // Declare and initialize Inside the constructor 
    System.Threading.Thread updateThread = new System.Threading.Thread(update); 
} 
0

这一切都没有错误消息基本上是 - 如果你敢读the docs他们声明:

线程程序可以是静态方法或实例方法。

因此,要么使用一个静态方法或从你的构造在同一类的东西,如:

System.Threading.Thread updateThread = new System.Threading.Thread(myObj.update); 
+0

问题不在于'正在引用update'方法,其*正在被引用。它需要被移动到'.ctor'或其他非静态方法。 –

+0

鉴于 - 编辑相应。 – cacau