【发布时间】:2010-11-29 08:45:19
【问题描述】:
我正在开发一个使用多线程的服务器程序。问题是,有多个类和很多线程,都需要访问某个 TextBox。 (tbLog)
方法(Log)如下所示:
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;
}
}
}
当然,我尝试过其他事情,这不是我最好的尝试之一。问题是,即使我像这样从另一个线程/类调用该方法:
namespace Server.Connections
{
class packetSend
{
static bool sendPacket(string rawPacket)
{
Menu menu = new Menu();
menu.Log("I'm a message");
return true;
}
}
}
-它只能在主线程中工作。我猜它与命名空间有关,或者因为我正在使用:
Menu menu = new Menu();
答案可能很明显,但我没有看到。 叹息
非常感谢您的帮助。
【问题讨论】:
标签: c# winforms multithreading invoke