我有一个包含事件和自定义EventArgs的类。有意义的代码:
public void OnTickReceived(TickReceivedEventArgs e)
{
EventHandler<TickReceivedEventArgs> handler = TickReceived;
if (handler != null)
handler(this, e);
}
public event EventHandler<TickReceivedEventArgs> TickReceived = delegate { };并使用UI Windows窗体中的类来订阅事件,如下所示
private void button4_Click(object sender, EventArgs e)
{
bool esito;
t = new T3OpenStockReader();
esito = t.Connect();
textBox1.Text += "Connection: " + esito.ToString() + "\r\n";
Application.DoEvents();
if (esito)
{
esito = t.Subscribe("MI.EQCON.2552");
textBox1.Text += "Subscription: " + esito.ToString() + "\r\n";
Application.DoEvents();
}
if (esito)
{
t.Start();
t.TickReceived += NewTick_Event;
System.Diagnostics.Debug.Print("Reading started...");
}
}
private void NewTick_Event(object sender, TickReceivedEventArgs e)
{
textBox1.Text += e.tick.DT + " " + e.tick.Price + " " + e.tick.Volume + "\r\n";
}我收到一个InvalidOperationException - cross.thread操作。我做错了什么?
发布于 2013-10-09 03:21:59
I收到InvalidOperationException - cross.thread操作。我的错误在哪里?
假设T3OpenStockReader在它自己的线程上引发事件--但您正在尝试修改事件处理程序中的UI……这意味着你在错误的线程中做了。您可能应该将事件处理程序更改为类似以下内容:
private void NewTick_Event(object sender, TickReceivedEventArgs e)
{
Action action = () => textBox1.Text += e.tick.DT + " " + e.tick.Price
+ " " + e.tick.Volume + "\r\n";
textBox1.BeginInvoke(action);
}我还建议你摆脱你的Application.DoEvents()调用-它们是试图在UI线程中做太多事情的症状。
发布于 2013-10-09 03:22:15
我假设您正在尝试更新非UI线程上的UI组件,即NewTick_Event。您需要强制更新回到UI线程上,例如
private void NewTick_Event(object sender, TickReceivedEventArgs e)
{
textBox1.Invoke(new Action(() => textBox1.Text += e.tick.DT + " " + e.tick.Price + " " + e.tick.Volume + "\r\n"));
}发布于 2013-10-09 03:27:30
从另一个线程调用NewTick_Event,并且必须在UI线程上调用对控件的更改(例如,使用BeginInvoke方法)。
private void NewTick_Event(object sender, TickReceivedEventArgs e)
{
this.BeginInvoke( (Action) () =>
{
textBox1.Text += e.tick.DT + " " + e.tick.Price + " " + e.tick.Volume + "\r\n";
});
}https://stackoverflow.com/questions/19256428
复制相似问题