避免使用Dispatcher.BeginInvoke

时间:2016-03-04 15:05:50

标签: c# multithreading asynchronous

我正在编写一个库来控制TCP上的应用程序。连接是异步处理的,所以我在通信类中添加了一个事件来指示已收到消息。

public event EventHandler<MessageRecievedEventArgs> MessageRecieved; 

但是当我举起事件时,主类中的事件处理程序在TCP线程上执行事件处理程序而不是主线程。

如何避免要求用户通过调用来更新GUI?

    private void MessageRecieved(object sender, MessageRecievedEventArgs e)
    {
        Dispatcher.BeginInvoke((Action)(()=> { textBox1.Text = e.Message; }));
    }

1 个答案:

答案 0 :(得分:2)

Using Hans Passant's comment above, I just modified my code as follows:

    private SynchronizationContext MainUIThread; //as a class field

In the constructor:

public MyClass()
{
      MainUIThread = SynchronizationContext.Current;
}

Modification to the event structure:

    public event EventHandler<MessageRecievedEventArgs> MessageRecieved;

    protected virtual void OnMessageReceived(object sender, MessageRecievedEventArgs args)
    {
        var handle = MessageRecieved;

        if (handle == null)
            return;

        if(MainUIThread  != null)
        {
            MainUIThread.Post(d => handle(sender, args), this);
        }
        else
        {
            handle(sender, args);
        }
    }