Skip to main content
 首页 » 编程设计

c#之跨线程冲突

2024年02月13日1452php

我有一个包含事件和自定义 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 线程中执行过多操作的症状。