1

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.
user3014282
  • 209
  • 2
  • 12

2 Answers2

2

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

Michael
  • 1,557
  • 2
  • 18
  • 38
1

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.

Orion_Eagle
  • 124
  • 5
  • I'm just learning programming so could you explain why it would be better to not use separate thread? I wanted that some actions(they will take some time) will be executed on this thread every x seconds while other thread will be checking/doing something else. – user3014282 Feb 20 '14 at 00:36