How to update UI in WPF application from thread?

I'm writing a client/server application and I'm trying to update UI from a thread that contains an infinite loop, in order to perform Socket.Receive. When I receive a packet on the socket, I have to update the UI and continue with the loop. The problem is that the thread can't manage the UI, so I tried to call BeginInvoke inside the thread, but the result was that UI froze. Is there a simple procedure that allows to call BeginInvoke inside a thread and returns the control to UI?

Upvotes: 2

Views: 8219

Answers (1)

GregorMohorko
GregorMohorko

Reputation: 2877

Use a blocking invoke to update UI on the main thread. This way, the thread will wait for the update to finish, and then continue. You were invoking in a non-blocking async way, which probably flooded the main thread and that's why it froze.

System.Windows.Application.Current.Dispatcher.Invoke(delegate{
    // update UI
});

Upvotes: 6

Related Questions