c# - 使用非静态方法的线程

标签 c# multithreading

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

我的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.

最佳答案

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

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

我很确定这样可以很好地工作

关于c# - 使用非静态方法的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895347/

相关文章:

c# - openxml sdk excel如何解析和计算公式

c# - WPF 绑定(bind)如何区分索引器属性和列表元素?

c# - 如何在 Asp.net 2.0 C# 中显示另存为对话框?

python - 在不同设置中使用以及引用 GIL 时,术语 I/O 会出现混淆

java - Java封装线程安全代码的最佳实践是什么

c++ - 为什么8线程比2线程慢?

c# - 来自 LLVM 绑定(bind)的不平衡堆栈警告

c# - .NET 多个 gmail 帐户与 2 个网络浏览器控件

java - 多个线程执行相同的方法(非同步)行为

Java线程等待和通知方法