Ensuring that things run on the UI thread in WPF

前端 未结 1 431
花落未央
花落未央 2020-12-02 12:17

I\'m building a WPF application. I\'m doing some async communication with the server side, and I use event aggregation with Prism on the client. Both these things results in

相关标签:
1条回答
  • 2020-12-02 13:13

    Going over each of your questions, one by one:

    1. Not quite; you should only invoke onto the UI thread when necessary. See #2.
    2. Yes, it does matter. You should not just automatically Invoke everything. The key is to only invoke onto the UI thread if necessary. To do this, you can use the Dispatcher.CheckAccess method.
    3. That is correct.
    4. Also correct, and yes, you do run the risk of less responsive programs. Most of the time, you are not going to be looking at a severe performance hit (we're talking about milliseconds for a context switch), but you should only Invoke if necessary. That being said, at some points it is unavoidable, so no, I would not say it is bad practice at all. It is just one solution to a problem that you will encounter every now and then.
    5. In every case I have seen, I have made due with Dispatcher.CurrentDispatcher. For complex scenarios, this may not be sufficient, but I (personally) have not seen them.
    6. Not entirely correct, but this line of thinking will not do any harm. Let me put it this way: the Dispatcher can be used to gain access to the UI thread for the application. But it is not in and of itself the UI thread.
    7. BackgroundWorker is generally used when you have a time-consuming operation and want to maintain a responsive UI while running that operation in the background. Normally you do not use BackgroundWorker instead of Invoke, rather, you use BackgroundWorker in conjunction with Invoke. That is, if you need to update some UI object in your BackgroundWorker, you can Invoke onto the UI thread, perform the update, and then return to the original operation.
    8. Yes. The UI thread of a WPF application, by definition, must be running in a single-threaded apartment.

    There's a lot to be said about BackgroundWorker, I'm sure many questions are already devoted to it, so I won't go into too much depth. If you're curious, check out the MSDN page for BackgroundWorker class.

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