gpt4 book ai didi

c# - 跨线程冲突

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:07 25 4
gpt4 key购买 nike

我有一个包含事件和自定义 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 操作。我做错了什么?

最佳答案

I receive InvalidOperationException - cross.thread operation. Where my error?

大概 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 线程中执行过多操作的症状。

关于c# - 跨线程冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19256428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com