跨线程问题 [英] Cross Thread problem
本文介绍了跨线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了这段代码(lg_log是一个列表框,我希望它记录start_server.bat),这是我得到的代码:
I got this code (lg_log is a listbox, and i want it to log the start_server.bat) Here is the code i got:
public void bt_play_Click(object sender, EventArgs e)
{
lg_log.Items.Add("Starting Mineme server ..");
string directory = Directory.GetCurrentDirectory();
var info = new ProcessStartInfo(directory + @"\start_base.bat") {UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WorkingDirectory = directory + @"\Servers\Base"};
var proc = new Process { StartInfo = info, EnableRaisingEvents = true };
proc.OutputDataReceived += (obj, args) =>
{
if (args.Data != null)
{
lg_log.Items.Add(args.Data);
}
};
proc.Start();
proc.BeginOutputReadLine();
lg_log.Items.Add("Server is now running!");
proc.WaitForExit();
}
运行此命令时,我会得到一个错误..
When i run this, I'll get an error ..
我得到的错误是这样:System.InvalidOperationException希望它会有所帮助:)
The error i get is this: System.InvalidOperationException Hope it helps :)
错误来自lg_log.Items.Add(args.Data);代码行
The error comes at the lg_log.Items.Add(args.Data); code line
推荐答案
替换
if (args.Data != null)
{
lg_log.Items.Add(args.Data);
}
使用
if (args.Data != null)
{
if (lg_log.InvokeRequired)
lg_log.Invoke(new Action(() => lg_log.Items.Add(args.Data)));
else
lg_log.Items.Add(args.Data);
}
这篇关于跨线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文