【问题标题】:Thread using non-static method使用非静态方法的线程
【发布时间】:2014-02-20 09:05:21
【问题描述】:

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

我的windows窗体代码是这样的:

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 秒调用一次 refresh(),但定时器不是问题。 我收到线程错误:

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

【问题讨论】:

标签: c# multithreading


【解决方案1】:

在 button1_click() 函数中,您可以使用 lambda 在另一个线程中调用您的刷新方法:

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

我很确定这样会很好地工作

【讨论】:

    【解决方案2】:

    如果您使用计时器进行刷新,那么我认为您不需要单独的线程来刷新。

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

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

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

    【讨论】:

    • 我只是在学习编程,所以你能解释一下为什么不使用单独的线程会更好吗?我希望每隔 x 秒在该线程上执行一些操作(它们将需要一些时间),而其他线程将检查/执行其他操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多