Dillinger
Dillinger

Reputation: 1903

Can't use thread with non-static method

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?

Upvotes: 3

Views: 2331

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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

Upvotes: 4

wingerse
wingerse

Reputation: 3796

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).

Upvotes: 3

Related Questions