c# - 跨线程冲突

标签 c# multithreading winforms

我有一个包含事件和自定义 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/

相关文章:

c# - 为应用程序提供与 Visual Studio 相同的视觉外观

c# - 在没有焦点的情况下在 C# 中打开表单

c# - 如何隐藏实时图表中的背景网格线?

C多线程嵌套for循环-超参数网格搜索的组合爆炸问题

c# - MemoryBarrier 是否保证所有内存的内存可见性?

c# - 如何沿轴旋转字符串列表?

c# - StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别?

javascript - 在 javascript Google Analytics 中使用 C# 变量,变量范围

c - 不确定为什么会产生这么多线程

c# - 如何显示来自另一种形式的数据