C#从不同线程调用控件

编程入门 行业动态 更新时间:2024-10-22 07:29:24
本文介绍了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

非常感谢帮助.

推荐答案

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

调用通常如何工作:

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

  • 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#从不同线程调用控件

    本文发布于:2023-11-12 12:27:07,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1581497.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:线程   控件

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!