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

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

问题描述

我已经搜查一吨,但我似乎无法找到与我的具体问题的任何事情。

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

我希望能够从另一个类(SocketListener)更新我的MainUI的形式和范围内,我有一个处理网络(clientThread)线程。现在,我可以运行从网络线程简单的输出,如写调试器输出和创建一个消息。

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.

但我真正想要做的是能够从会做的事情对我的MainUI实例clientThread调用code。我怎样才能做到这一点?

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?

此外,如果有人想的code特定部分的话,我可以将它张贴,以帮助给你一个更好的理解我在问什么。

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.

祝商祺!

推荐答案

检查<一href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx"><$c$c>InvokeRequired控制类的,如果这是真的,然后调用的 调用 并传递一个委托(通常是匿名的方式),做你想要做的客户端的线程上的东西。

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天全站免登陆