user3014282
user3014282

Reputation: 209

Thread using non-static method

I'm trying to write a simple tool(it contains only one class), but I stuck on threads. I dont know how to run thread with non-static method.

My code of windows form is something like that:

public partial class Form1 : Form
{
   //--Some methods here--//
   void login();
   void start();
   void refresh();

   //--Button events--//
   private void button1_Click()
   {
       //I want to start thread here
       //Something like Thread t = new Thread(new ThreadStart(refresh));
       //t.Start();
   }
}

With timer this thread should call refresh() every x seconds, but timer isnt problem. I'm getting error with thread:

A field initializer cannot reference the non-static field, method, or property.

Upvotes: 1

Views: 2060

Answers (2)

Orion_Eagle
Orion_Eagle

Reputation: 134

If you are using a timer for refreshing, then I do not think you need separate thread to refresh.

Or if you want to asynchronously invoke the refresh from timer_callback, you can create an Action delegate and call BeginInvoke on it.

Action ac = new Action(this.refresh);
ac.BeginInvoke(null, null);

Edit : If you use System.Threading.Timer, it itself runs on another thread. So starting thread from this timer call back is not suggested. Check this.

Upvotes: 1

Michael
Michael

Reputation: 1607

In the button1_click() function, you can call your refresh method in another thread using lambda:

new Thread(
        () =>
        {
            refresh();
        }
        ).Start();

I'm pretty sure it will work well that way

Upvotes: 2

Related Questions