可取消可报告进度的Task
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp2
{
public partial class MainWindow : Window
{
CancellationTokenSource Cts = new CancellationTokenSource();
public MainWindow()
{
Person p = new Person();
p.Do(Cts.Token, new Progress<int>((xpp)=>label.Content=xpp));
}
/// <summary>
/// 按钮按下事件处理函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
Cts.Cancel();
}
}
public class Person
{
public string name { get; set; }
public string age { get; set; }
public int length { get; set; }
public void Do(CancellationToken token, IProgress<int> progress)
{
Action action = new Action(() =>
{
try
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(1000);
//报告进度
progress.Report(i);
//如果用户执行CancellationTokenSource.Cancel()方法就抛出异常
//从而达到取消线程操作
token.ThrowIfCancellationRequested();
}
}
catch (Exception)
{
Console.WriteLine("取消线程执行");
}
});
Task task = new Task(action,token);
task.Start();
}
}
}
这里有一点需要说明,那就是Progress实际上是跨线程修改控件,去system.Progress源码中找到Report的源码中调用了OnReport函数,如下图:
m_synchronizationContext变量是个SynchronizationContext类型,用于线程间通信。