且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不同的类更新来自不同的线程的UI

更新时间:2023-02-05 08:53:57

下面是我想做到这一点,我创建了这样的形式的方法:

Here is how I like to do this, I create a method on the form like this:

public void AddItemToList(string Item)
{
   if(InvokeRequired)
      Invoke(new Action<string>(AddItemToList), Item);
   else
      listBox1.Add(Item);
}

我preFER调用在这种情况下,确保了项目同步增加,否则他们可以走出秩序。如果你不关心的顺序,那么你可以使用的BeginInvoke 这将是一个稍快一点。由于这种方法是公共的,你都可以从任何类在应用程序中,只要你能得到一个引用到窗体。

I prefer invoke in this case to make sure the items are added synchronously, otherwise they can get out of order. If you don't care about the order then you can use BeginInvoke which will be a tad faster. Since this method is public, you can all it from any class in your application as long as you can get a reference to your form.

这样做的另一个好处是,你可以从你的UI线程或一个非UI线程调用它,它需要决定是否需要调用 ING的护理。这样,你的来电者并不需要知道哪个线程运行它们的。

Another advantage of this is that you can call it from either your UI thread or a non-UI thread and it takes care of deciding whether or not it needs Invokeing. This way your callers don't need to be aware of which thread they are running on.

更新 为了满足您对如何获得引用表格注释,通常在Windows窗体应用程序,你的Program.cs文件看起来是这样的:

UPDATE To address your comment about how to get a reference to the Form, typically in a Windows Forms app your Program.cs file looks something like this:

static class Program
{
   static void Main() 
   {
       MyForm form = new MyForm();
       Application.Run(form);  
   }

}

这是通常我会做什么,特别是在一个单表申请的情况下:

This is typically what I would do, particularly in the case of a "Single Form" application:

static class Program
{
   public static MyForm MainWindow;

   static void Main() 
   {
       mainWindow = new MyForm();
       Application.Run(form);  
   }

}

然后你就可以访问它pretty的任何地方多用:

And then you can access it pretty much anywhere with:

Program.MainWindow.AddToList(...);