c# - Rx.NET 在所有回调之后再次直接调用函数

标签 c# wpf multithreading serial-port system.reactive

我想与串行端口进行通信 - 获取一些数据。我想尽可能快地循环获取这些数据。因此,我有带有回调的 GetData() 函数,它在 WPF 表单上绘制数据。如何在所有回调之后立即循环调用此 GetData 函数?

比如循环GetData->Draw->GetData->Draw等等?

更新:Mb类似这样的东西吗?

var ob = Observable.Create<Data>(
  observer => {
    while(true) {
      observer.OnNext(GetDataFromSerialPort());
    }
});

最佳答案

我将创建一个通过可观察序列公开串行端口数据的服务。然后我会将其注入(inject)到我的 MVVM 堆栈中。

该服务希望与您所拥有的类似,但具有处置功能

public class MySerialPortService : IsCancellationRequested
{
    public IObservable<Data> GetData()
    {
        return Observable.Create<Data>(async (o, cts) =>
          observer => {
            while (!cts.IsCancellationRequested) {
              observer.OnNext(GetDataFromSerialPort());
            }
        });
    }
}

public class MyViewModel : IDisposable
{
    private readonly IMySerialPortService _mySerialPortService;
    private readonly ISchedulerProvider _schedulerProvider;
    private readonly SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();

    public MyViewModel(IMySerialPortService mySerialPortService, ISchedulerProvider schedulerProvider)
    {
        _mySerialPortService = mySerialPortService;
        _schedulerProvider = schedulerProvider;
    }

    public void Start()
    {
        _subscription.Disposable = _mySerialPortService.GetData()
            .SubscribeOn(_schedulerProvider.Background) //or _schedulerProvider.ThreadPool, or CreateEventLoopScheduler or what ever you do internally.
            .ObserveOn(_schedulerProvider.Foreground)   //or _schedulerProvider.Dispatcher etc...
            .Subscribe(
                val=> Update(val),
                ex=> ...
            )
    }

    public void Dispose()
    {
        _subscription.Dispose();
    }
}

以下帖子可能会有所帮助 - https://github.com/LeeCampbell/RxCookbook/tree/master/IO/Disk 。它逐步向您展示如何创建从磁盘读取的可观察序列。您可以将磁盘 IO 替换为串行端口 IO。

关于c# - Rx.NET 在所有回调之后再次直接调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35546406/

相关文章:

c# - 从新窗口绑定(bind) WPF

wpf - 所有 WPF 窗口中的页眉和页脚相同

java - 在 Java 中使用并行求解时出现越界异常

c# - 如何使用 FluentScheduler 库在 C# 中安排任务?

c# - 如何使用 Xamarin 在 iOS 8 中制作表格单元格和分隔符全宽?

c# - 在 c# 中,当向方法发送参数时,我们应该什么时候使用 "ref"什么时候使用 "out"以及什么时候不使用它们?

c# - 在 WPF 中绘制和删除形状

c# - 将 Generic<Derived> 转换为 Generic<Base>

c++ - 在已经存在的类上调用一个线程而不是创建一个

multithreading - 同时执行多个线程循环的并发编程?