Unresponsive UI when using BeginInvoke

前端 未结 3 1708
野性不改
野性不改 2021-01-24 15:22

Bckground
I have a networked application written in C#. my server program has a UI and several communication threads, that read from tcp sockets and display

相关标签:
3条回答
  • 2021-01-24 15:51

    Invoke shouldn't lead to deadlocks unless you own a lock while you're doing the invoking... but BeginInvoke shouldn't make the UI unresponsive either. Could the problem be that you're simply trying to update the textbox too often? Perhaps buffer the incoming text more? For example, only update the UI once every half second rather than any time you read any data.

    0 讨论(0)
  • 2021-01-24 15:51

    You are calling BeginInvoke() too often. The UI thread will dispatch the delegate before it does its normal duties, like painting controls and responding to the mouse. If the delegate target is doing a lot of work (appending text to an RTB is expensive) or you are simply flooding it with requests, it doesn't get around to doing its normal job anymore. The UI will freeze. That happens pretty easily, about a 1000 invokes per second is enough.

    The key to solve this is to realize that it is wasted effort to invoke so often. The human eye can't perceive updates faster than 25 times per second. So buffer the text until 50 milliseconds have passed since the last update. Environment.TickCount is a cheap timer.

    Also beware that you might actually produce text faster than can be appended to the RTB. That requires throttling the thread. That's easy: use Invoke instead of BeginInvoke.

    0 讨论(0)
  • 2021-01-24 15:52

    You're probably simply spending all your time setting the text.

    Try replacing the RichTextBox with an ordinary TextBox; it should be much faster.

    0 讨论(0)
提交回复
热议问题