How to start a thread to keep GUI refreshed?

前端 未结 4 2035
北恋
北恋 2021-02-11 03:39

I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed,

4条回答
  •  隐瞒了意图╮
    2021-02-11 04:06

    It should be fine as it is. Things which may be freezing your UI:

    • Are you locking within the UI thread, and locking on the same lock in your other thread?
    • Are you calling Join on the thread from your UI thread?
    • Are you doing some other heavy work in the UI thread?

    If you could come up with a short but complete program which shows the problem, I'm sure we could help to fix it... but it certainly should be okay.

    EDIT: Okay, now you've added this:

    The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

    So you're updating the property from the non-UI thread? I would expect that to cause problems, because it will trigger UI changes from the wrong thread.

    I suggest you take an approach such as:

    • Periodically update the counter via Dispatcher.BeginInvoke
    • Have the "UI counter" and the "worker counter" - and copy the value from the "worker counter" to the "UI counter" in the UI thread via a DispatcherTimer, essentially polling it.

提交回复
热议问题