Rx.NET Call函数在所有它的回调之后再次指向

时间:2016-02-22 05:32:38

标签: 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());
    }
});

1 个答案:

答案 0 :(得分:4)

我会创建一个通过可观察序列公开串行端口数据的服务。然后我会将它注入我的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。它将逐步显示如何创建从磁盘读取的Observable Sequence。您可以将磁盘IO交换为串行端口IO。