This question描述了如何确保 IObservable<>.Throttle
通过将 UI 调度程序传递给 Throttle
在 UI 线程上运行.但是,我的 Observables 是在基于 .NET Standard 1.5 的共享库中定义的。有没有等价于DispatcherScheduler.Instance
在 .NET Standard 中,还是应该从使用(WPF/UWP/等)库中注入(inject)调度程序?
最佳答案
.NET Standard 的 System.Reactive 程序集中不存在 DispatcherScheduler 类。
可能的解决方法是将 SynchronizationContextScheduler
与当前 SynchronizationContext
一起使用。当调用 ObserveOn()
时,当您在 UI 线程上时,可观察对象的处理程序将在 UI 线程上运行。
当 ObserveOn()
未在 UI 线程上调用时,整个过程将不起作用。为避免这种情况,您可以创建类似 AppContext
对象的东西,在 UI 初始化发生时对其进行设置,并使其在您的应用程序中可分发。将 SynchronizationContext.Current
保存在此 AppContext
中,您可以在拥有 AppContext
的任何地方创建 UI 线程观察者。
IObservable<EventArgs> myObservable = GetSomeObservableEvents();
var myScheduler = new SynchronizationContextScheduler(SynchronizationContext.Current);
myObservable.ObserveOn(myScheduler).Subscribe(ev =>
{
// some code that should run on UI thread
});
我在 Xamarin.Forms 2.5.0 项目中像这样使用它,我在 .NET Standard 2.0 中有一个包含 ViewModels、Views 等的应用程序项目。
此答案(至少)在这种情况下有效:
- .NET Standard 项目版本为 2.0
- System.Reactive 的版本是 4.0.0-preview00001
关于c# - 在 .NET Standard 库中访问 Dispatcher IScheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859550/