我有简单的表单应用程序,该应用程序包含单独的套接字任务。此任务处理向服务器发送消息的
send(string)
过程。服务器向客户端发送回消息,任务接收消息并引发事件,调用最后一个onReceived() { Console.WriteLine(“{0}”, e.Message)}
。这一切都非常有效。
我的问题是:当 RichEditBox 代码添加到“onReceived”事件处理程序方法中时,为什么此过程不起作用?
onReceived
与 Console.Writeline(“Message”);
有效。
onReceived
与任何 RichEditBox
对象均无效。
例如,这不起作用:
communicator.onReceived(object sender, ExtraEventArgs e)
{
richTextBox.AppendText(“Message”);
}
为了进行全面审查,您使用的代码必须包含在问题中。
无论如何,我认为如何管理“分离套接字任务”很重要。如果您在程序中的某个位置使用“BackgroundWorker”,请改用“System.Windows.Forms.Timer”。在控制台中调用简单的写入命令与像 RichEditBox 这样更复杂的表单控件有很大不同。
如果您使用无限循环在循环内不时调用“Application.DoEvents()”,那就太好了。可能是您的代码中的某个地方阻塞并干扰了 Windows 窗体的正常功能。
如果我想做一个简单的解决方案来解决问题,当然它不是很专业,那就是将文本保存在“communicator.onReceived”方法内部的一个字段中,而不是直接使用RichTextBox,然后激活计时器,然后计时器将字段中的文本添加到 RichTextBox,然后清空字段并自行停用,或者更专业的方法是使用所需形式的“Invoke”来完成工作。
类似于下面的代码:
private void communicator.onReceived(object sender, ExtraEventArgs e)
{
AppendTextToRichTextBoxIndirectly("Message", AddingTextMethod.UsingInvoke);
}
public enum AddingTextMethod
{
UsingTimer = 1,
UsingInvoke = 2
}
protected string TheTextToBeAdded = "";
public void AppendTextToRichTextBoxIndirectly(string Text, AddingTextMethod AddMethodType = AddingTextMethod.UsingInvoke)
{
switch (AddMethodType)
{
case AddingTextMethod.UsingInvoke:
this.Invoke(new Action(() => AppendTextToRichTextBoxDirectly(Text)));
break;
case AddingTextMethod.UsingTimer:
TheTextToBeAdded = Text;
TimerForAddingText.Interval = 100;
TimerForAddingText.Start();
break;
}
}
void TimerForAddingText_Tick(object sender, EventArgs e)
{
TimerForAddingText.Stop();
AppendTextToRichTextBoxDirectly(TheTextToBeAdded);
TheTextToBeAdded = "";
}
public void AppendTextToRichTextBoxDirectly(string Text)
{
richTextBox.AppendText(Text);
}