C# Windows 窗体应用程序 - 从另一个线程和类更新 GUI? [英] C# Windows Forms Application - Updating GUI from another thread AND class?

查看:20
本文介绍了C# Windows 窗体应用程序 - 从另一个线程和类更新 GUI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了大量搜索,但似乎找不到与我的具体问题相关的任何内容.

I've searched a ton, but I can't seem find anything relating to my specific problem.

我希望能够从另一个类 (SocketListener) 更新我的 MainUI 表单,并且在其中我有一个处理网络的线程 (clientThread).现在,我可以从网络线程运行简单的输出,例如写入调试器输出并创建 MessageBox.

I want to be able to update my MainUI form from another class (SocketListener) and within that I have a thread that handles the networking (clientThread). Right now I can run simple outputs from the networking thread such as writing to the debugger output and creating a MessageBox.

但我真正想做的是能够从 clientThread 调用代码,这些代码将在我的 MainUI 实例上执行操作.我该怎么做?

But what I really want to do is be able to invoke code from the clientThread that will do things on my MainUI instance. How can I do this?

此外,如果有人想要代码的特定部分,那么我可以发布它以帮助您更好地理解我的要求.

Also, if anyone wants specific portions of the code then I can post it to help give you a better understanding of what I'm asking.

最好的问候!

推荐答案

检查 InvokeRequiredControl 类,如果为真,则调用Invoke 并传入一个委托(通常是匿名方法),它可以在客户端线程上执行您想要执行的操作.

Check the InvokeRequired of the Control class, and if it's true, then call the Invoke and pass in a delegate (usually an anonymous method) that does what you want to do on the client's thread.

示例:

public void DoWork(Form form)
{
    if (form.InvokeRequired)
    {
        // We're on a thread other than the GUI thread
        form.Invoke(new MethodInvoker(() => DoWork(form)));
        return;
    }

    // Do what you need to do to the form here
    form.Text = "Foo";
}

这篇关于C# Windows 窗体应用程序 - 从另一个线程和类更新 GUI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆