在multiThread中更新UI的最佳方法是什么

时间:2013-08-12 10:05:05

标签: c# multithreading winforms uiapplicationdelegate

我有三个类,其中两个是UI类,在mainForm类中,我通过执行

启动一个新表单
new LoginForm.ShowDialog();

在LoginForm类中,我编写了有关登录和注销的代码,当使用时,我启动一个新线程来检查是否需要执行某些操作,并更新数据库;这是问题,我不知道如何更新MainForm中的标签 我搜索这个问题他们告诉我我应该使用Delegate.but它真的很困惑我因为他们不在同一个类中所以我不知道如何使用Delegate交叉线程和交叉不同 到现在为止,我的代码是这样的 MainForm.cs:

public partial class MainForm : Form
        public delegate void testDelegate();
        public MainForm()
        {
            InitializeComponent();
        }
        public void msg(string s)
        {
            label.Test = s;
        }
}

LoginForm.cs:

JobDoer jD = new JobDoer();
Thread t2 = new Thread(new ThreadStart(jD.run));
t2.Start();

JobDoer:

public void run()
 {
     //tD();
     tD = new MainForm.testDelegate(MainForm.msg);
     //this.
     Thread.Sleep(1000);
     return;
}

接下来该怎么做?

2 个答案:

答案 0 :(得分:0)

取自:Best Way to Invoke Any Cross-Threaded Code?

您还可以使用扩展方法和lambdas来使代码更清晰。

using System.ComponentModel;
public static class ISynchronizeInvokeExtensions
{
  public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
  {
    if (@this.InvokeRequired)
    {
      @this.Invoke(action, new object[] { @this });
    }
    else
    {
      action(@this);
    }
  }
}

所以现在你可以在任何ISynchronizeInvoke上使用InvokeEx,并且能够访问实现类的属性和字段。

this.InvokeEx(f => f.listView1.Items.Clear());

答案 1 :(得分:0)

对于这种事情,有
System.ComponentModel.BackgroundWorker类。 https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-implement-a-form-that-uses-a-background-operation。 它为您处理线程同步,并具有有用的进度更新事件