Cross Thread problem
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 ..
Edit: The error i get is this: System.InvalidOperationException Hope it helps :)
The error comes at the lg_log.Items.Add(args.Data); code line
Replace
if (args.Data != null)
{
lg_log.Items.Add(args.Data);
}
with
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);
}
lg_log.Items.Add(args.Data);
This line might get executed on a different thread than the UI thread. Use this.BeginInvoke(...) to update the UI on the UI Thread.
To verify the execution on a non-UI htread note that the message of the InvalidOperation will state Cross-thread access to the UI
this.BeginInvoke(new Action<string>(UpdateUI(args.Data));
....
private void UpdateUI(string data)
{
lg_log.Items.Add(data);
}
精彩评论