Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Highly-Concurrent Cross-Thread UI Access

In C# I have several workers that do work and I need to reflect this into the UI. Update a progress bar, add items to a list and so on.

First time I tried to do this, I prepared everything with locks to make sure only one thread accesses the UI at every given moment but I got an exception. So I learned I need to use the Dispatcher.Invoke to access and change UI elements. It's quite cumbersome to enclose each UI change into an invoke but I can deal with it.

My questions:

  • Is it necessary to synchronize the Dispatcher.Invoke calls or is that done internally? So I wonder if I need to add another layer of protection with locks...
  • Does it impact performance having many update requests queued into the dispatcher? So if several threads work and each of them reflects into the UI with a small change, how does issuing many calls to Dispatcher.Invoke` affect performance? Should I use a timer and only update UI once a second and queue all the UI changes internally?
  • Is there an easier way to do cross-thread access more inline... without Invokes?
like image 870
CodeAngry Avatar asked Dec 26 '22 05:12

CodeAngry


1 Answers

The human brain won't be able to process 200 updates/sec. It will just slow down your UI and not gain you anything.

Instead, make a timer that polls for status every, say, 200ms. This will be fast enough (5 updates/sec) not to be noticeable.

No need to lock on the dispatcher, it's handled internally. But you should dedicate your tasks to the computations, and not manipulate the UI from them. Implement a timer like I said, and use some standard way of cross-thread communication to retrieve the current status from the UI thread.

like image 83
Lucas Trzesniewski Avatar answered Dec 27 '22 20:12

Lucas Trzesniewski