C#从不同线程调用控件 [英] C# Invoke control from different thread

查看:92
本文介绍了C#从不同线程调用控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用多线程处理服务器程序.问题是,有多个类和很多线程,所有这些类都需要访问特定的TextBox.(tbLog)

I'm working on a server program, which uses multithreading. The problem is, there are multiple classes and alot of threads, which all need access to a certain TextBox. (tbLog)

方法(Log)如下所示:

The method (Log) looks like like this:

using System;
using System.Windows.Forms;
using System.ComponentModel;

namespace Server
{
    public delegate void Logs(string message);

    public partial class Menu : Form
    {    
        public Menu()
        {
            InitializeComponent();
        }

        public void Log(string message)
        {
            if (this.tbLog.InvokeRequired)
                this.tbLog.BeginInvoke(new MethodInvoker(delegate() { tbLog.Invoke(new Logs(Log)); }
            )); 
            else
                this.tbLog.Text += DateTime.Now + ": " + message + Environment.NewLine;
        }
    }
}

当然,我还尝试了其他方法,但这不是我更好的尝试之一.问题是,即使我从另一个这样的线程/类中调用该方法,也是如此:

Ofcourse I've tried other things, and this is not one of my better tries. The problem is, even if I call the method from another thread/class like this:

namespace Server.Connections
{
    class packetSend
    {
        static bool sendPacket(string rawPacket)
        {
            Menu menu = new Menu();

            menu.Log("I'm a message");

            return true;
        }
    }
}

-它只能在主线程中工作.而且我猜想它与名称空间有关,或者因为我在使用:

-it will only work from the main thread. And I guess it has something to do with the namespace or because I'm using:

Menu menu = new Menu();

答案可能很明显,但我没有看到.叹气

The answer is probably obvious, but I'm not seeing it. sigh

非常感谢帮助.

推荐答案

为什么每次记录消息时都要创建一个新表单?

调用通常如何工作:

  1. 例如应用程序启动时,您将创建一个显示日志的表单.这是在主线程上;

  1. With e.g. application startup, you create a form which displays the log. This is on the main thread;

然后,当您需要登录时,您会获得对该表格的引用;

Then, when you need to log, you get a reference to that form;

然后,通过 Invoke 将日志发送到该表单.

Then, with Invoke, you send the log to that form.

如果您确实需要即时创建表单,还应该使用 Invoke 来创建新表单.您可以通过获取对主表单的引用来完成此操作,并在该表单上使用 Invoke 来创建表单.

If you do need to create the form on the fly, the Invoke should also be used to create the new form. You can do this by getting a reference to your main form and use Invoke on that form to also create the form.

您看到的问题是因为您是在没有消息循环的非UI线程上创建 Menu 表单.

The problem you are seeing is because you are creating the Menu form on a non-UI thread which does not have a message loop.

这篇关于C#从不同线程调用控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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