C#: Invoke GUI interaction from Thread

Problem

Lets say the following method is called by a thread and should display the received data in the UI:

    public void ParseData(string data)
    {
        buffer.Append(data);
        textBoxLog.Text = buffer.ToString();
        textBoxLog.SelectionStart = textBoxLog.Text.Length;
        textBoxLog.ScrollToCaret();            
    } 

This example will throw an exception, as the thread cannot modify information on the UI thread.

Solution

The solution is to define a delegate and a method:

    public delegate void SetLog();

    private void SetLog_R()
    {          
        textBoxLog.Text = buffer.ToString();
        textBoxLog.SelectionStart = textBoxLog.Text.Length;
        textBoxLog.ScrollToCaret();

    }

In the original method, we instantiate the delegate and invoke the delegate von the UI element:

    public void ParseData(string data)
    {
        buffer.Append(data);
        SetLog sl = new SetLog(SetLog_R);
        textBoxLog.Invoke(sl);
    } 

Thats it.

Parameters

You can also use parameters:

private delegate void AddItemDelegate(ListViewItem item);

private void AddItem(ListViewItem item)
{
    listEvents.Items.Insert(0, item);
}

The call of the delegate:

AddItemDelegate dg = new AddItemDelegate(AddItem);
listEvents.Invoke(dg, item);


Datenschutzerklärung | Impressum