C#中的Dispatcher


C#中BackgroundWorker

使用前提

在WPF程序中,有一些比较耗时的后台操作时,比如向远程服务器请求数据,或者通过TCP/IP为某台设备提供升级固件服务等等。为了防止这类操作freeze用户界面,造成用户体验下降,即程序假死的状况出现。一种常见的,更user friendly的方式是,提供一个进度条窗口,提示用户该操作的完成进度。并提供取消操作的选项。

C#中的 BackgroundWorker Class 则是执行该任务的最佳选择。

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, theBackgroundWorker class provides a convenient solution.
-MSDN

关于 BackgroundWorker 类

主要属性

  • CancellationPending - 只读属性,default值为false,执行CancelAsync方法后,值为true。表明应用程序请求了取消后台操作。
  • IsBusy - 如果后台异步操作开始执行,值为true,否则为false
  • WorkerReportProgress - 如果BackgroundWorker支持后台操作进程更新,设置值为true,default值为false

主要事件

  • DoWork
  • ProgressChanged
  • RunWorkerCompleted
    不要再DoWork事件处理程序中对UI线程中的对象进行操作,操作应该放在ProgressChanged和RunWorkerCompleted的事件处理程序中。

主要方法

  • RunWorkerAsync() - 执行后台操作,激发DoWork事件
  • ReportProgress()- 激发ProgressChanged事件
  • CancelAsync() - 提交终止后台操作的请求,并将CancellationPending属性值设为true。在程序其他地方要定时检查CancellationPending属性的值,作出相应操作,比如
if (worker.CancellationPending) { e.Cancel = true; } 

示例程序

XAML

<Window x:Class="BackgroundWorkerExample.MainWindow"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        Title="MainWindow" Height="150" Width="300">
    <StackPanel>
        <ProgressBar Name="progressBar" Height="20" Width="250" Margin="10"></ProgressBar>
        <TextBox Name="textBox" Width="50" Height="20" HorizontalAlignment="Center"></TextBox>
        <Button Name="btnProcess" Width="100" Click="btnProcess_Click" Margin="5">Start</Button>
        <Button Name="btnCancel" Width="100" Click="btnCancel_Click" Margin="5">Cancel</Button>
    </StackPanel>
</Window>

C#

namespace BackgroundWorkerExample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { BackgroundWorker bgworker = new BackgroundWorker(); public MainWindow() { InitializeComponent(); bgworker.WorkerReportsProgress = true; bgworker.WorkerSupportsCancellation = true; bgworker.DoWork += bgworker_DoWork; bgworker.ProgressChanged += bgworker_ProgressChanged; bgworker.RunWorkerCompleted += bgworker_RunWorkerCompleted; } void bgworker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <= 100; i++) { if (worker.CancellationPending) { e.Cancel = true; } else { worker.ReportProgress(i); Thread.Sleep(100); } } } void bgworker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; textBox.Text = e.ProgressPercentage.ToString(); } void bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { progressBar.Value = 0; if (e.Cancelled) { MessageBox.Show("Background task has been canceled", "info"); } else { MessageBox.Show("Background task finished", "info"); } } private void btnProcess_Click(object sender, RoutedEventArgs e) { if (!bgworker.IsBusy) { bgworker.RunWorkerAsync(); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { bgworker.CancelAsync(); } } } 

演示

 
BackgroundWorkerExample.gif


作者:Jason_Yuan
链接:https://www.jianshu.com/p/b89f39c5f803
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

今天要说的是WPF程序员处理多线程的另外一个方式 - Dispatcher

当我们打开一个WPF应用程序即开启了一个进程,该进程中至少包含两个线程。

  • 一个线程用于处理呈现:隐藏在后台运行
  • 一个线程用于管理用户界面:接收输入、处理事件、绘制屏幕以及运行应用程序代码。即UI线程。

在UI线程中有一个Dispatcher对象,管理每一个需要执行的工作项。Dispatcher会根据每个工作项的优先级排队。向Dispatcher列队中添加工作项时可指定10个不同的级别。那么问题来了,如果遇到耗时操作的时候,该操作如果依旧发生在UI线程中,Dispatcher 列队中其他的需要执行的工作项都要等待,从而造成界面假死的现象。为了加快响应速度,提高用户体验,我们应该尽量保证Dispatcher 列队中工作项要。所以,对于耗时操作,我们应该开辟一个新的子线程去处理,在操作完成后,通过向UI线程的Dispatcher列队注册工作项,来通知UI线程更新结果。

Dispatcher提供两个注册工作项的方法:Invoke 和 BeginInvoke。这两个方法均调度一个委托来执行。Invoke 是同步调用,也就是说,直到 UI 线程实际执行完该委托它才返回。BeginInvoke是异步的,将立即返回。

  • Dispatcher实际上并不是多线程
  • 子线程不能直接修改UI线程,必须通过向UI线程中的Dispatcher注册工作项来完成
  • Dispatcher 是单例模式,暴露了一个静态的CurrentDispatcher方法用于获得当前线程的Dispatcher
  • 每一个UI线程都至少有一个Dispatcher,一个Dispatcher只能在一个线程中执行工作。
  • 开启新线程的方法很多,比如delegate.BeginInvoke()的方式开启的新线程。

Delegate.Invoke: Executes synchronously, on the same thread.
Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.

示例程序

XAML

<Window x:Class="DispatcherExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="160" Width="300">
    <StackPanel>
        <ProgressBar Name="progressBar" Height="20" Width="250" Margin="10"></ProgressBar>
        <TextBox Name="textBox" Width="50" Height="20" HorizontalAlignment="Center"></TextBox>
        <Button Name="btnProcess" Width="100" Click="btnProcess_Click" Margin="5">Start</Button>
        <Button Name="btnCancel" Width="100" Click="btnCancel_Click" Margin="5">Cancel</Button>
    </StackPanel>
</Window>

C#

namespace DispatcherExample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } Thread taskThread; private void btnProcess_Click(object sender, RoutedEventArgs e) { taskThread = new Thread(DoTask); taskThread.Start(); } private void btnCancel_Click(object sender, RoutedEventArgs e) { taskThread.Abort(); MessageBox.Show("Background task finished normally", "info"); this.progressBar.Value = 0; this.textBox.Text = null; } private void DoTask() { Int64 InputNum = (Int64)100; for (Int64 i = 0; i < InputNum; i++) { Thread.Sleep(100); this.Dispatcher.BeginInvoke((Action)delegate() { this.progressBar.Value = i; this.textBox.Text = i.ToString(); }); } MessageBox.Show("Background task has been canceled", "info"); this.Dispatcher.BeginInvoke((Action)delegate() { this.progressBar.Value = 0; this.textBox.Text = null; }); } } } 

演示

 
DispatcherExample.gif


作者:Jason_Yuan
链接:https://www.jianshu.com/p/0714fc755988
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM