3

I'm trying to call a non static method called UpdateResults() from a thread. This is my code:

 class Live
 {
     Thread scheduler = new Thread(UpdateResults);

     public Live()
     { 
         scheduler.Start();
     }

     public void UpdateResults() 
     {
        //do some stuff
     }
}

but I get this error:

A field initializer can not refer to the property, method or non-static field 'Live.UpdateResults ()'

how can I fix this?

Dillinger
  • 1,823
  • 4
  • 33
  • 78

2 Answers2

4

C# 6.0 solution: change assign (=) to initialization =>

  class Live {
    // Please, note => instead of =
    Thread scheduler => new Thread(UpdateResults);

    public Live() {
      scheduler.Start();
    }

    public void UpdateResults() {
      //do some stuff
    }
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • This will effectively change it from field to property as => is only a syntactic sugar over standard getter – Fabjan Apr 28 '16 at 09:26
  • 1
    @Dillinger: the *syntax* is a lambda, but actually it's a kind of initializer (assigning the value on instance creation) – Dmitry Bychenko Apr 28 '16 at 09:35
  • 1
    It's not a lambda, it just uses the "lambda arrow" and it is equivalent to a getter property. Just syntax sugar. – wingerse Apr 28 '16 at 09:36
3

This has nothing to do with Thread. See this question for details as to why this is happening. To fix your problem, change your class as follows:

class Live
{
    Thread scheduler;

    public Live()
    { 
        scheduler = new Thread(UpdateResults);
        scheduler.Start();
    }

    public void UpdateResults() 
    {
       //do some stuff
    }
}

As Jon Skeet mentions in the aforementioned question, from section 10.5.5.2 of the C# 4 spec:

A variable initializer for an instance field cannot reference the instance being created. Thus it is a compile-time error to reference this in a variable initializer, because it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

When you write new Thread(UpdateResults) you are really writing new Thread(this.UpdateResults).

Community
  • 1
  • 1
wingerse
  • 3,670
  • 1
  • 29
  • 61
  • Just a question: on `Thread scheduler;` I get `Field 'LiveScore.scheduler' is assigned but its value is never used`, is just an alert. – Dillinger Apr 28 '16 at 09:21
  • 1
    Because you are using a private field only in the constructor. If you don't want to use the variable in another method, you might as well make it local to the constructor. The error will go away as soon as you reference the variable from another method – wingerse Apr 28 '16 at 09:22