C# 在多线程应用程序中访问RichTextBox会导致OutOfMemoryException
我可能只是做错了。我目前正在使用MSMQ和Web服务。我想了解MSMQ是如何工作的,所以我找到了一个贷款经纪人的学校例子 长话短说,我需要能够对我的系统进行压力测试,所以我希望能够生成(比如)100条消息,并通过我的消息系统发送它们。我想从Windows窗体应用程序中执行此操作,但问题出在这里。我有一个表单如下所示: 左边是一个自定义控件,右边是我的“控制台”窗口,它告诉我发生了什么。当我按下发送按钮时,它应该使用上面字段中给出的数据来发送消息。但当我按下发送按钮时,程序会冻结一段时间,然后点击C# 在多线程应用程序中访问RichTextBox会导致OutOfMemoryException,c#,multithreading,winforms,msmq,C#,Multithreading,Winforms,Msmq,我可能只是做错了。我目前正在使用MSMQ和Web服务。我想了解MSMQ是如何工作的,所以我找到了一个贷款经纪人的学校例子 长话短说,我需要能够对我的系统进行压力测试,所以我希望能够生成(比如)100条消息,并通过我的消息系统发送它们。我想从Windows窗体应用程序中执行此操作,但问题出在这里。我有一个表单如下所示: 左边是一个自定义控件,右边是我的“控制台”窗口,它告诉我发生了什么。当我按下发送按钮时,它应该使用上面字段中给出的数据来发送消息。但当我按下发送按钮时,程序会冻结一段时间,然后点
OutOfMemoryException
。这是Send
方法:
private void Send(List<SimpleRequest.LoanRequest> list)
{
int quantity = int.Parse(numericQuantity.Value.ToString());
int delay = int.Parse(numericDelay.Value.ToString());
if (list.Count == 1)
{
for (int threadnumber = 0; threadnumber < quantity; threadnumber++)
{
Task.Factory.StartNew(() => RequestLoanQuote(threadnumber, list[0]));
if (delay > 0)
{
Thread.Sleep(delay);
}
}
}
else
{
for (int threadnumber = 0; threadnumber < quantity; threadnumber++)
{
Task.Factory.StartNew(() => RequestLoanQuote(threadnumber, list[threadnumber]));
if (delay > 0)
{
Thread.Sleep(delay);
}
}
}
}
private void SetText(String msg)
{
if (this.console.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { msg });
}
else
{
this.console.Text += msg;
}
}
最后是SetText
方法:
private void Send(List<SimpleRequest.LoanRequest> list)
{
int quantity = int.Parse(numericQuantity.Value.ToString());
int delay = int.Parse(numericDelay.Value.ToString());
if (list.Count == 1)
{
for (int threadnumber = 0; threadnumber < quantity; threadnumber++)
{
Task.Factory.StartNew(() => RequestLoanQuote(threadnumber, list[0]));
if (delay > 0)
{
Thread.Sleep(delay);
}
}
}
else
{
for (int threadnumber = 0; threadnumber < quantity; threadnumber++)
{
Task.Factory.StartNew(() => RequestLoanQuote(threadnumber, list[threadnumber]));
if (delay > 0)
{
Thread.Sleep(delay);
}
}
}
}
private void SetText(String msg)
{
if (this.console.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { msg });
}
else
{
this.console.Text += msg;
}
}
因此Send
方法调用requestloanquete
方法,该方法调用SetText
方法。我不知道哪里出了问题,但可能是死锁。尝试使用,就像这样:
public static void SetText(this RichTextBox textBox, string msg)
{
Action append = () => textBox.AppendText(msg);
if (textBox.InvokeRequired)
textBox.BeginInvoke(append);
else
append();
}
this.console
是RichTextBox
,对吗?尝试使用。另外,请尝试使用而不是Invoke
@dbc谢谢你做到了这一点。你想把它作为一个答案吗?:)但有一个问题。它似乎没有按预期启动所有线程。如果我告诉它启动10个请求,它可能会先启动5个,然后启动其他5个,或者任意数量的剩余请求。不确定我做错了什么,或者这是否是由于多线程造成的。@Vipar-不是我的专业领域,但你实际上是在创建一个,对吗?我相信任务
实际上是一个非常轻量级的对象,当一个人空闲时,它会被分配到某个线程(一个较重的对象)上运行。也许可以问第二个更集中的问题?我可以试试。感谢您的尝试:)