Cross.Thread violation

I have a class with an event and a custom EventArgs. The meaningful code:

    public void OnTickReceived(TickReceivedEventArgs e)
    {
        EventHandler<TickReceivedEventArgs> handler = TickReceived;
        if (handler != null)
            handler(this, e);
    }

    public event EventHandler<TickReceivedEventArgs> TickReceived = delegate { };

and consuming the class in a UI Windows Form subscribing the event like this

    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"; 
    }

I receive an InvalidOperationException - cross.thread operation. What am I doing wrong?

Jon Skeet
people
quotationmark

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

Presumably T3OpenStockReader raises events on its own thread - but you're trying to modify the UI in your event handler... which means you're doing it in the wrong thread. You should probably change your event handler to something like:

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);
}

I'd also suggest that you get rid of your Application.DoEvents() calls - they're a symptom of trying to do too much in the UI thread.

people

See more on this question at Stackoverflow