Threads - what's going wrong

  • Thread starter Thread starter Jerry S
  • Start date Start date
J

Jerry S

Hi

This is probably simple, but can anyone explain why this won't work:

public void SomeMethod()
{
//Do stuff
}

ThreadStart myThreadDelegate = new ThreadStart(SomeMethod);
Thread myThread = new Thread(myThreadDelegate);

It gives me a "A field initializer cannot reference the nonstatic
field, method, or property..." error.

If I make the SomeMethod static, then it works properly. But if the
method is static then it can't access other non-static methods from
the class, so that's no good.

I realise that I'm not getting what's happening here because I know
virtually nothing about threads!

Thanks.

Jerry
 
Jerry S said:
This is probably simple, but can anyone explain why this won't work:
ThreadStart myThreadDelegate = new ThreadStart(SomeMethod);
Thread myThread = new Thread(myThreadDelegate);

It gives me a "A field initializer cannot reference the nonstatic
field, method, or property..." error.

Where did you place that "ThreadStart myThreadDelegate = ..." code? I think
you've placed it in a static method and then the exception makes sense.
Remember that static methods cannot access instance methods without an
object reference.

Here's what you can do:

public class MyClass {
public void SomeMethod() {
//Do stuff
}
public void Start() {
ThreadStart myThreadDelegate = new ThreadStart(SomeMethod);
Thread myThread = new Thread(myThreadDelegate);
}
public static void Main() {
MyClass mc = new MyClass();
mc.Start();
}
}

Regards,
Pieter Philippaerts
Managed SSL/TLS: http://www.mentalis.org/go.php?sl
 
Back
Top