w0f
w0f

Reputation: 958

Avoiding main thread lockup when delegating to GUI

I have a RichTextBox that the Console is redirected to. The Console Redirector delegates the AppendText() call each time the console is written to. However, the GUI locks up while the text is being appended, and since the log is written to in periods of rapid succession, the main thread/GUI locks up until the text is no longer being appended. Is there a way to allow control of the form while the log is being appended from another thread?

Upvotes: 1

Views: 66

Answers (2)

Thomas Andreè Wang
Thomas Andreè Wang

Reputation: 3429

All in all, no you cannot get away from the lockedness. The UI thread will be locked when working, and when you dispatch to it you are in essence saying, I want to run this piece of code on the UI thread.

To alleviate some of the "lockedness" you need to try to be "smart" about it.

  • Update as rarely as possible to manage this, use some sort of "buffer" to update. Possibly make a "fake" UI class (aka a model/DTO) fill it with data from your thread and flush it out to the UI when needed/on demand/on complete
  • In the delegates as much as possible. DO NOT perform any form of logic as that's work that will lock you for a longer period than needed.

I see that you are using winforms, if this is a project where you are in control, then go for WPF.

Upvotes: 2

Servy
Servy

Reputation: 203850

No, you cannot safely update the UI from a non-UI thread.

If you have other UI work that you want done you'll need to have your console redirect function simply spend less time updating the UI. Don't have it update the UI with everything all the time. Have it buffer the data and write to the UI less frequently, or throttle the console input if there is simply too much data to display everything (while also doing other necessary work).

Upvotes: 3

Related Questions