使用线程和MVVM将高速数据流式传输到WPF UI

时间:2011-08-24 19:50:36

标签: c# wpf multithreading c#-4.0 mvvm

我在使用新的WPF应用程序时遇到问题,该应用程序尝试向文本框显示高速字节流。字节来自一个串口,我已经制作了一个较旧的WinForms应用程序,处理流很好,有一个后台线程从串口读取并通过调用委托发布到UI。

现在这个WPF应用程序的问题是我正在使用基本的MVVM方法。 UI上的文本框绑定到VM上的属性,该属性基于INotifyPropertyChanged触发PropertyChanged事件。当数据准备通过读取串口的服务上的订阅事件发布到ui时,我使用以下内容:

Action dispatchAction = () => { FormattedStream += s; };
_currentDispatcher.Invoke(dispatchAction);

FormattedStream是UI绑定的VM字符串属性。

WPF应用程序在WinForms版本中没有发生的事情是WPF应用程序变得缓慢且无响应,因为它无法跟上流以及WinForms应用程序和根据我的任务经理,wpf app正在使用/需要更多的处理器。

我想知道的是,是否有一些解决方案来处理流式传输(高速)数据到WPF UI。

ETA:我也尝试使用BeginInvoke而不是Invoke,当使用BeginInvoke时,流会持续几秒钟然后冻结。调用是我可以连续流式传输到UI的唯一方法。

ETA:这是代码:

//窗口/视图

public partial class MainWindow : Window, IView
{
  public MainWindow()
  {
     InitializeComponent();
  }

  public IViewModel ViewModel
  {
     get { return DataContext as IViewModel; }
     set { DataContext = value; }
  }

  public void ScrollToCaret()
  {
     txtBoxOutPut.ScrollToEnd();

     if (txtBoxOutPut.Text.Length > 10000)
        txtBoxOutPut.Text = txtBoxOutPut.Text.Remove(0, 9000);
  }

  public event Action ComPortSelected;
  public event Action StartPortReader;
  public event Action StopPortReader;


  private void Start_Click(object sender, RoutedEventArgs e)
  {
     StartPortReader.Invoke();
  }

  private void Stop_Click(object sender, RoutedEventArgs e)
  {
     StopPortReader.Invoke();
  }

}

// ViewModel

public class ViewModel : IViewModel, INotifyPropertyChanged

{       private readonly ISerialPortReaderService _portReaderService;       private readonly Dispatcher _currentDispatcher;

  public ViewModel(IView view, ISerialPortReaderService portReaderService)
  {
     View = view;
     View.ViewModel = this;
     View.StartPortReader += View_StartPortReader;
     View.StopPortReader += View_StopPortReader;
     _portReaderService = portReaderService;
     _currentDispatcher = Dispatcher.CurrentDispatcher;
     _portReaderService.ByteArrived += _portReaderService_ByteArrived;
  }

  private void _portReaderService_ByteArrived(string s)
  {
     Action dispatchAction = () => { FormattedStream = s; };
     _currentDispatcher.Invoke(dispatchAction);
  }

  private void View_StopPortReader()
  {
     _portReaderService.Stop();
  }

  private void View_StartPortReader()
  {
     _portReaderService.Start(SelectedPort);
  }

  public IView View { get; private set; }

  public void ShowView()
  {
     View.Show();
  }

  private StringBuilder _FormattedStream = new StringBuilder();
  public string FormattedStream
  {
     get
     {
        return _FormattedStream.ToString();
     }
     set
     {
        _FormattedStream.Append(value);
        PropertyChanged(this, new PropertyChangedEventArgs("FormattedStream"));
        View.ScrollToCaret();
     }
  }

  private string _SelectedPort;
  public string SelectedPort
  {
     get
     {
        return _SelectedPort;
     }
     set
     {
        _SelectedPort = value;
        PropertyChanged(this, new PropertyChangedEventArgs("SelectedPort"));
     }
  }

  public ReadOnlyCollection<string> AvailablePorts
  {
     get { return GetAvailablePorts(); }
  }

  private ReadOnlyCollection<string> GetAvailablePorts()
  {
     var ports = System.IO.Ports.SerialPort.GetPortNames();
     return new ReadOnlyCollection<string>(ports.ToList());
  }

  public event PropertyChangedEventHandler PropertyChanged = delegate { };

}

//串行端口阅读器服务

public class SerialPortReaderService : ISerialPortReaderService

{       private SerialPort _port = new SerialPort();       私人只读IThreadRunner _threadRunner;

  public SerialPortReaderService(IThreadRunner threadRunner)
  {
     _threadRunner = threadRunner;
  }

  public void Start(string comPort)
  {
     if (_port != null && !_port.IsOpen)
     {
        _port.PortName = comPort;
        _port.BaudRate = 4800;            
        _port.Open();

        _threadRunner.Start(() =>
                               {

                                     var b = new byte[20];
                                     var bArray = _port.Read(b, 0, 20);
                                     foreach (var b1 in b)
                                     {
                                        next10Bytes.Append(b1 + ", ");
                                     }                                        

                                     BytesArrived(next10Bytes.ToString());
                                     next10Bytes.Clear();

                                     Thread.Sleep(10);

                               });
     }
  }

  private StringBuilder next10Bytes = new StringBuilder();

  public void Stop()
  {
     if (_port.IsOpen)
     {
        _threadRunner.Stop();
        _port.Close();
     }
  }

  public event Action<string> BytesArrived;

}

//我使用的线程管理器

public class ThreadRunner : IThreadRunner

{       私有线程_thread;       私人布尔_isRunning;

  /// <summary>
  /// Will continuously run in a while loop the action submitted in a separate thread
  /// </summary>
  /// <param name="toDoAction"></param>
  public void Start(Action toDoAction)
  {
     if (_thread != null && _thread.IsAlive)
        Stop();

     _isRunning = true;

     _thread = new Thread(() =>
                             {
                                while (_isRunning)
                                {
                                   toDoAction.Invoke();
                                }
                             });
     _thread.Start();
  }

  public void Stop()
  {
     _isRunning = false;
     if (_thread != null && _thread.IsAlive)
     {
        _thread.Abort();
        _thread.Join(new TimeSpan(0, 0, 1));
     }
  }

  public bool ThreadIsRunning
  {
     get { return _isRunning; }
  }

}

1 个答案:

答案 0 :(得分:0)

从Petoj提到的我创建了一个新窗口,仍然使用流媒体服务,但只有窗口本身订阅了bytesarrived事件并通过Dispatcher.Invoke手动附加到txtbox并且低,看到解决了问题,没有减速并没有大量的CPU使用率。

故事的道德之处在于,每次添加到字符串时,绑定或至少绑定到一个字符串会导致速度变慢。