Which is better MainThread.Being/Invoke... VS Dispatcher.Dispatch... #7518
-
In MAUI, we now have multiple ways to execute code on the Main/Dispatcher/UI thread. The BindableObjects now have a From the outside, both of these offer essentially the same subset of functionality. There might be situational differences for when you would want to call these though (i.e. do I currently have a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Good question. So you are correct, there are different ways to invoke on the main thread:
All 3 use the same mechanisms under the hood since both use platform APIs to get to the main thread. However, the main difference is the fact that the Dispatcher is coming from a UI object, so always knows which thread to use. The MainThread is static so it is mostly correct. Let me explain. When you have a UI component (BindableObject, Button, Page, Window), it knows which thread it is assigned to. Some platforms, like Windows and iOS, require that UI objects be created on the UI thread. It will throw otherwise. And, the dispatcher is initialized to that thread. MainThread has no concept of the UI thread so picks the first one. In most cases, it is correct because most platforms only have 1 "main thread". Windows is an outlier to this because it supports windows on separate threads. The current implementation is actually going to pick the current window that is in focus - which is correct 90% of the time since by default apps share a single UI thread. However, if the user was to instantiate a new window in a new thread, then MainThread would switch when the other window is selected. So, what is the "correct" way to do things? Well, mostly I would say use dispatcher if you can - keep in mind that you can pass the There is also a If you have a VM that needs a dispatcher, the best way would be to use |
Beta Was this translation helpful? Give feedback.
Good question.
So you are correct, there are different ways to invoke on the main thread:
BindableObject.Dispatcher.Dispatch()
Dispatcher.GetForCurrentThread().Dispatch()
MainThread.BeginInvokeOnMainThread()
All 3 use the same mechanisms under the hood since both use platform APIs to get to the main thread. However, the main difference is the fact that the Dispatcher is coming from a UI object, so always knows which thread to use. The MainThread is static so it is mostly correct. Let me explain.
When you have a UI component (BindableObject, Button, Page, Window), it knows which thread it is assigned to. Some platforms, like Windows and iOS, require that UI objects be created on the UI t…