Dispatcher为线程的调度器,最常见是Application.Current.Dispatcher.Invoke(...)在UI线程上执行一些内容,在某些场景下可将Dispatcher放入Action、或者通过Action将参数传递给UI线程的Dispatcher,以实现在其他线程上(如定时器)中调用UI线程执行一些内容;
- WPF
-
Application.Current.Dispatcher: UI线程的Dispatcher;
-
Dispatcher.CurrentDispatcher:当前线程的Dispatcher,线程没有Dispatcher就自动关联一个;
-
FrameworkElement.Dispatcher:该控件所属线程的Dispatcher;
- MAUI
-
Application.Current.Dispatcher: UI线程的Dispatcher;
-
Microsoft.Maui.Dispatching.Dispachter.GetForCurrentThread():当前线程的Dispatcher,没有更换则返回null;
-
Element.Dispatcher:该控件所属线程的Dispatcher;
-
IPlatformApplication.Current.Services.GetRequiredService<IDispathcer>():从DI容器中直接拿Dispathcer,IPlatformApplication是MAUI自带的DI容器访问接口,WPF和Avalonia都没有,IPlatformApplication.Current.Services就是MauiApp.CreartBuilder().Service;
- Avalonia
-
Avalonia.Threading.Dispatcher.UIThread.Invoke(...):UI线程上直接执行;
-
Visual.Dispatcher:该控件所属线程的Dispatcher,就是UIThread的Dispathcer,与WPF、MAUI不同;