Task-based Asynchronous Pattern基于任务的异步模式 (TAP) 是基于 System.Threading.Tasks 命名空间中的 Task 和 Task 类型,这些类型用于表示任意异步操作。 TAP 是用于新开发的建议的异步设计模式。
工具/原料
1MS visual studio Express 2012 for windows phone
方法/步骤
2后台代码设计namespace ProgressReportDemo{ public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); } // 测试任务进度监控 private void Button_Click_1(object sender, RoutedEventArgs e) { // 创建IProgress对象来监控任务进度 Progress progress = new Progress(); // 订阅进度改变事件处理 progress.ProgressChanged += new EventHandler(progress_ProgressChanged); // 启动异步任务并且使用进度回报 DoSomething(progress); } // 进度变化事件处理 void progress_ProgressChanged(object sender, ProgressPartialResult value) { progressBar.Value = (float)value.Current / value.Total * 100; } // 开始异步任务 private async void DoSomething(IProgress progress) { int total = 100; for (int i = 0; i <= total; i++) { await Task.Delay(20); //等待2秒钟 if (progress != null) { // 报告任务进度情况 progress.Report(new ProgressPartialResult() { Current = i + 1, Total = total }); ///每次循环发生新的变化 ///通过 } } progress.Report(new ProgressPartialResult() { Current = 0, Total = total }); } // 进度返回的对象数据 public class ProgressPartialResult { public int Current { get; set; } public int Total { get; set; } } }}
4创建IProgress对象来监控任务进度请调用 Report 方法并将对象。调用 Report方法将引发 ProgressChanged 事件,您将单独处理该事件。
注意事项