2014-02-20 53 views
1

我想写一个简单的工具(它只包含一个类),但我坚持线程。 我不知道如何使用非静态方法运行线程。线程使用非静态方法

我的窗户形式的代码是类似的东西:

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(); 
    } 
} 

随着计时器这个线程应该调用刷新()每x秒,但计时器心不是问题。 我收到提示螺纹:

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

你没有贴生成此编译错误的代码。 –

+1

看这里http://stackoverflow.com/questions/7400677/a-field-initializer-cannot-reference-the-non-static-field-method-or-property –

回答

1

如果您使用的是定时器清爽,那么我不认为你需要单独的线程来刷新。

或者,如果您想异步调用timer_callback的刷新,则可以创建一个Action委托并调用BeginInvoke。

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

编辑: 如果使用System.Threading.Timer,它本身运行在另一个线程。所以不建议从这个定时器回调线程开始。检查this

+0

我只是学习编程,所以你可以解释为什么不使用单独的线程会更好? 我希望某些动作(它们需要一些时间)将在每个x秒内在该线程上执行,而其他线程将检查/执行其他操作。 – user3014282

2

在Button1_Click的()函数,你可以使用lambda打电话给你的刷新方法在另一个线程:

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

我敢肯定这将工作做好这样