0

I'm trying to run a method on a separate thread, but when I try initializing the the new thread I get this error:

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

The update method:

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);
}

I am getting an error on the initializer:

System.Threading.Thread updateThread = new System.Threading.Thread(update);
Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
  • 2
    http://stackoverflow.com/questions/12659551/threading-problems-in-c-sharp-a-field-initializer-cannot-reference-the-non-stat This might help you. – Nil23 Jan 09 '14 at 07:30
  • Or this: http://stackoverflow.com/questions/2642978/how-to-call-the-method-in-thread-with-aruguments-and-return-some-value – Christophe De Troyer Jan 09 '14 at 07:34

2 Answers2

1

Where are you put your decalartion for Thread ? Do you can try to put it on your constructor please ?

Like this :

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

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

   // Declare and initialize Inside the constructor
   System.Threading.Thread updateThread = new System.Threading.Thread(update);
}
Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86
0

It's all there in the error message basically - if you dare to read the docs they state:

Thread procedures can be static methods or instance methods.

So either use a static method or from your constructor in the same class something like:

System.Threading.Thread updateThread = new System.Threading.Thread(myObj.update);
cacau
  • 3,606
  • 3
  • 21
  • 42
  • The issue is not the way the `update` method is being referenced, its *where* it is being referenced. It needs to be moved to the `.ctor` or another non-static method. – Sam Axe Jan 09 '14 at 07:36