我有一个设想。(Windows Forms, c#, .NET)

There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load method the UI become nonresponsive for the duration for load method execution. To overcome this I load data on different thread (trying to change existing code as little as I can) I used a background worker thread which will be loading the data and when done will notify the application that it has done its work. Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.

伪代码看起来像这样:

代码1

UserContrl1_LoadDataMethod()
{
    if (textbox1.text == "MyName") // This gives exception
    {
        //Load data corresponding to "MyName".
        //Populate a globale variable List<string> which will be binded to grid at some later stage.
    }
}

它给出的例外是

跨线程操作无效:从创建该控件的线程以外的线程访问的控件。

为了了解更多关于这一点,我做了一些谷歌搜索,并提出了一个建议,如使用以下代码

代码2

UserContrl1_LoadDataMethod()
{
    if (InvokeRequired) // Line #1
    {
        this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
        return;
    }

    if (textbox1.text == "MyName") // Now it won't give an exception
    {
    //Load data correspondin to "MyName"
        //Populate a globale variable List<string> which will be binded to grid at some later stage
    }
}

但我似乎还是回到了原点。再次申请 变得反应迟钝。这似乎是由于第1行if条件的执行。加载任务再次由父线程完成,而不是由我生成的第三个线程完成。

我不知道我认为这是对还是错。

我如何解决这个问题,以及执行第1行if块的效果是什么?

情况是这样的:我想根据控件的值将数据加载到全局变量中。我不想改变子线程中控件的值。我不会从子线程中做。

因此只有访问值,才能从数据库中获取相应的数据。


当前回答

UI中的线程模型

为了理解基本概念,请阅读UI应用程序中的线程模型(旧的VB链接在这里)。该链接导航到描述WPF线程模型的页面。但是,Windows窗体利用了相同的思想。

UI线程

只有一个线程(UI线程)被允许访问System.Windows.Forms.Control及其子类成员。 试图从不同的线程访问System.Windows.Forms.Control的成员会导致跨线程异常。 因为只有一个线程,所以所有的UI操作都作为工作项进入该线程:

如果UI线程没有工作,那么就存在空闲间隙,可以由与UI无关的计算使用。 为了使用上述间隙,请使用System.Windows.Forms.Control.Invoke或System.Windows.Forms.Control.BeginInvoke方法:

BeginInvoke和Invoke方法

The computing overhead of method being invoked should be small as well as computing overhead of event handler methods because the UI thread is used there - the same that is responsible for handling user input. Regardless if this is System.Windows.Forms.Control.Invoke or System.Windows.Forms.Control.BeginInvoke. To perform computing expensive operation always use separate thread. Since .NET 2.0 BackgroundWorker is dedicated to performing computing expensive operations in Windows Forms. However in new solutions you should use the async-await pattern as described here. Use System.Windows.Forms.Control.Invoke or System.Windows.Forms.Control.BeginInvoke methods only to update a user interface. If you use them for heavy computations, your application will block:

调用

System.Windows.Forms.Control.Invoke导致单独的线程等待,直到调用的方法完成:

BeginInvoke

System.Windows.Forms.Control.BeginInvoke不会导致单独的线程等待被调用的方法完成:

代码的解决方案

阅读问题的答案如何更新GUI从另一个线程在c# ? 对于c# 5.0和。net 4.5,推荐的解决方案在这里。

其他回答

这里有一种替代方法,如果您正在处理的对象没有

(InvokeRequired)

如果您使用的是类中的主窗体,而不是主窗体中的对象,但该对象在主窗体中,但没有invokerrequired,那么这是非常有用的

delegate void updateMainFormObject(FormObjectType objectWithoutInvoke, string text);

private void updateFormObjectType(FormObjectType objectWithoutInvoke, string text)
{
    MainForm.Invoke(new updateMainFormObject(UpdateObject), objectWithoutInvoke, text);
}

public void UpdateObject(ToolStripStatusLabel objectWithoutInvoke, string text)
{
    objectWithoutInvoke.Text = text;
}

它的工作原理与上面的相同,但是如果你没有一个带有invokerequired的对象,但是可以访问MainForm,那么它是一种不同的方法

同样的问题:如何从c中的另一个线程更新gui

两种方式:

在e.result中返回值,并使用它来设置backgroundWorker_RunWorkerCompleted事件的文本框值 在一个单独的类中声明一些变量来保存这些类型的值(它将作为数据持有者)。创建该类的静态实例,您可以在任何线程上访问它。

例子:

public  class data_holder_for_controls
{
    //it will hold value for your label
    public  string status = string.Empty;
}

class Demo
{
    public static  data_holder_for_controls d1 = new data_holder_for_controls();
    static void Main(string[] args)
    {
        ThreadStart ts = new ThreadStart(perform_logic);
        Thread t1 = new Thread(ts);
        t1.Start();
        t1.Join();
        //your_label.Text=d1.status; --- can access it from any thread 
    }

    public static void perform_logic()
    {
        //put some code here in this function
        for (int i = 0; i < 10; i++)
        {
            //statements here
        }
        //set result in status variable
        d1.status = "Task done";
    }
}

我有这个问题与FileSystemWatcher,并发现下面的代码解决了这个问题:

焊。SynchronizingObject = this

然后,控件使用当前表单对象处理事件,因此将位于同一线程上。

当我在xamarin工作室外的一个visual studio winforms原型项目中编程iOS-Phone单触摸应用程序控制器时,我发现了这个需求。比起xamarin studio,我更倾向于在VS中编程,我希望控制器能够与手机框架完全分离。通过这种方式,在Android和Windows Phone等其他框架上实现这个功能将更容易用于未来的使用。

我想要一种解决方案,使GUI可以响应事件,而无需处理每次单击按钮背后的跨线程切换代码。基本上让类控制器来处理,以保持客户端代码简单。你可能在GUI上有很多事件,如果你可以在类的一个地方处理它,会更干净。我不是一个多头专家,让我知道,如果这是有缺陷的。

public partial class Form1 : Form
{
    private ExampleController.MyController controller;

    public Form1()
    {          
        InitializeComponent();
        controller = new ExampleController.MyController((ISynchronizeInvoke) this);
        controller.Finished += controller_Finished;
    }

    void controller_Finished(string returnValue)
    {
        label1.Text = returnValue; 
    }

    private void button1_Click(object sender, EventArgs e)
    {
        controller.SubmitTask("Do It");
    }
}

GUI表单不知道控制器正在运行异步任务。

public delegate void FinishedTasksHandler(string returnValue);

public class MyController
{
    private ISynchronizeInvoke _syn; 
    public MyController(ISynchronizeInvoke syn) {  _syn = syn; } 
    public event FinishedTasksHandler Finished; 

    public void SubmitTask(string someValue)
    {
        System.Threading.ThreadPool.QueueUserWorkItem(state => submitTask(someValue));
    }

    private void submitTask(string someValue)
    {
        someValue = someValue + " " + DateTime.Now.ToString();
        System.Threading.Thread.Sleep(5000);
//Finished(someValue); This causes cross threading error if called like this.

        if (Finished != null)
        {
            if (_syn.InvokeRequired)
            {
                _syn.Invoke(Finished, new object[] { someValue });
            }
            else
            {
                Finished(someValue);
            }
        }
    }
}

我发现需要在与表单相关的所有方法中随意放置的检查和调用代码太冗长且不需要。下面是一个简单的扩展方法,可以让你完全摆脱它:

public static class Extensions
{
    public static void Invoke<TControlType>(this TControlType control, Action<TControlType> del) 
        where TControlType : Control
        {
            if (control.InvokeRequired)
                control.Invoke(new Action(() => del(control)));
            else
                del(control);
    }
}

然后你可以简单地这样做:

textbox1.Invoke(t => t.Text = "A");

没有更多的混乱-简单。