Search code examples
c#wpfdispatcher

Dispatcher on an event by itself and through delegate


I have a 3rd party DLL which I receive data from a device through network socket. Foo_WorkCompleted is an event subscribed to an action when data is received and is automatically fired. My first try is to check if the thread has been accessed, and if not, call itself again from a new thread to update the UI. But I receive threading exception that it is occupied. Then I tried calling a delegate from the dispatcher, that works.

I do not see difference between the two. An event should just work like a delegate. So, why one works but not the other. Would someone please help explain?

This does not work (threading exception):

private void Foo_WorkCompleted(object sender, WorkCompletedEventArgs e)
{
    if (Dispatcher.CheckAccess())
    {
        Dispatcher.BeginInvoke(
        (EventHandler<WorkCompletedEventArgs>)Foo_WorkCompleted, sender, e);
        return;
    }

    SomeMethod();
}

This works:

private delegate void UpdateUIDelegate();

private void Foo_WorkCompleted(object sender, WorkCompletedEventArgs e)
{      
     Dispatcher.BeginInvoke(
           DispatcherPriority.Send, new UpdateUIDelegate(SomeMethod));
}

Solution

  • You are using CheckAccess reversed, if the calling thread is the main thread for the dispatcher it will return true, so you need to do the invoke if it returns false:

    private void Foo_WorkCompleted(object sender, WorkCompletedEventArgs e)
    {
        if (!Dispatcher.CheckAccess())
        {
            Dispatcher.BeginInvoke(
            (EventHandler<WorkCompletedEventArgs>)Foo_WorkCompleted, sender, e);
            return;
        }
    
        SomeMethod();
    }