重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress
作者:webabcd
介绍
重新想象 Windows 8 Store Apps 之 异步编程
- IAsyncAction - 无返回值,无进度值
- IAsyncOperation - 有返回值,无进度值
- IAsyncActionWithProgress - 无返回值,有进度值
- IAsyncOperationWithProgress - 有返回值,有进度值
示例
1、演示 IAsyncAction(无返回值,无进度值)的用法
Thread/Async/IAsyncActionDemo.xaml
- <Page
- x:Class="XamlDemo.Thread.Async.IAsyncActionDemo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:XamlDemo.Thread.Async"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
- <Grid Background="Transparent">
- <StackPanel Margin="120 0 0 0">
- <TextBlock Name="lblMsg" FontSize="14.667" />
- <Button Name="btnCreateAsyncAction" Content="执行一个 IAsyncAction" Click="btnCreateAsyncAction_Click_1" Margin="0 10 0 0" />
- <Button Name="btnCancelAsyncAction" Content="取消" Click="btnCancelAsyncAction_Click_1" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- </Page>
Thread/Async/IAsyncActionDemo.xaml.cs
- /*
- * 演示 IAsyncAction(无返回值,无进度值)的用法
- *
- * 注:
- * 1、WinRT 中的异步功能均源自 IAsyncInfo
- * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
- *
- *
- * 另:
- * Windows.System.Threading.ThreadPool.RunAsync() - 返回的就是 IAsyncAction
- */
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Threading.Tasks;
- using Windows.Foundation;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- namespace XamlDemo.Thread.Async
- {
- public sealed partial class IAsyncActionDemo : Page
- {
- private IAsyncAction _action;
- public IAsyncActionDemo()
- {
- this.InitializeComponent();
- }
- private IAsyncAction GetAsyncAction()
- {
- // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncAction
- return AsyncInfo.Run(
- (token) => // CancellationToken token
- Task.Run(
- () =>
- {
- token.WaitHandle.WaitOne();
- token.ThrowIfCancellationRequested();
- },
- token));
- }
- private void btnCreateAsyncAction_Click_1(object sender, RoutedEventArgs e)
- {
- _action = GetAsyncAction();
- // 可以 await _action
- // IAsyncAction 完成后
- _action.Completed =
- (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
- {
- // AsyncStatus 包括:Started, Completed, Canceled, Error
- lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
- };
- lblMsg.Text = "开始执行,3 秒后完成";
- }
- // 取消 IAsyncAction
- private void btnCancelAsyncAction_Click_1(object sender, RoutedEventArgs e)
- {
- if (_action != null)
- _action.Cancel();
- }
- }
- }
2、演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
Thread/Async/IAsyncOperationDemo.xaml
- <Page
- x:Class="XamlDemo.Thread.Async.IAsyncOperationDemo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:XamlDemo.Thread.Async"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
- <Grid Background="Transparent">
- <StackPanel Margin="120 0 0 0">
- <TextBlock Name="lblMsg" FontSize="14.667" />
- <Button Name="btnCreateAsyncOperation" Content="执行一个 IAsyncOperation" Click="btnCreateAsyncOperation_Click_1" Margin="0 10 0 0" />
- <Button Name="btnCancelAsyncOperation" Content="取消" Click="btnCancelAsyncOperation_Click_1" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- </Page>
Thread/Async/IAsyncOperationDemo.xaml.cs
- /*
- * 演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
- *
- * 注:
- * 1、WinRT 中的异步功能均源自 IAsyncInfo
- * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
- */
- using System;
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Threading.Tasks;
- using Windows.Foundation;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- namespace XamlDemo.Thread.Async
- {
- public sealed partial class IAsyncOperationDemo : Page
- {
- private IAsyncOperation<int> _operation;
- public IAsyncOperationDemo()
- {
- this.InitializeComponent();
- }
- private IAsyncOperation<int> GetAsyncOperation(int x, int y)
- {
- // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperation<TResult>
- return AsyncInfo.Run<int>(
- (token) => // CancellationToken token
- Task.Run<int>(
- () =>
- {
- token.WaitHandle.WaitOne();
- token.ThrowIfCancellationRequested();
- // 返回结果
- return x * y;
- },
- token));
- }
- private void btnCreateAsyncOperation_Click_1(object sender, RoutedEventArgs e)
- {
- _operation = GetAsyncOperation(, );
- // 可以 await _operation
- // IAsyncOperation<TResult> 完成后
- _operation.Completed =
- (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
- {
- // AsyncStatus 包括:Started, Completed, Canceled, Error
- lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
- if (asyncStatus == AsyncStatus.Completed)
- {
- lblMsg.Text += Environment.NewLine;
- // 获取异步操作的返回结果
- lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
- }
- };
- lblMsg.Text = "开始执行,3 秒后完成";
- }
- // 取消 IAsyncOperation<TResult>
- private void btnCancelAsyncOperation_Click_1(object sender, RoutedEventArgs e)
- {
- if (_operation != null)
- _operation.Cancel();
- }
- }
- }
3、演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
Thread/Async/IAsyncActionWithProgressDemo.xaml
- <Page
- x:Class="XamlDemo.Thread.Async.IAsyncActionWithProgressDemo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:XamlDemo.Thread.Async"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
- <Grid Background="Transparent">
- <StackPanel Margin="120 0 0 0">
- <TextBlock Name="lblMsg" FontSize="14.667" />
- <TextBlock Name="lblProgress" FontSize="14.667" />
- <Button Name="btnCreateAsyncActionWithProgress" Content="执行一个 IAsyncActionWithProgress" Click="btnCreateAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />
- <Button Name="btnCancelAsyncActionWithProgress" Content="取消" Click="btnCancelAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- </Page>
Thread/Async/IAsyncActionWithProgressDemo.xaml.cs
- /*
- * 演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
- *
- * 注:
- * 1、WinRT 中的异步功能均源自 IAsyncInfo
- * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
- */
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Threading.Tasks;
- using Windows.Foundation;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- namespace XamlDemo.Thread.Async
- {
- public sealed partial class IAsyncActionWithProgressDemo : Page
- {
- private IAsyncActionWithProgress<int> _action;
- public IAsyncActionWithProgressDemo()
- {
- this.InitializeComponent();
- }
- private IAsyncActionWithProgress<int> GetAsyncActionWithProgress()
- {
- // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncActionWithProgress<TProgress>
- return AsyncInfo.Run<int>(
- (token, progress) => // CancellationToken token, IProgress<TProgress> progress
- Task.Run(
- () =>
- {
- // 报告进度(进度是一个 int 值)
- progress.Report();
- int percent = ;
- while (percent < )
- {
- token.WaitHandle.WaitOne();
- token.ThrowIfCancellationRequested();
- percent++;
- // 报告进度(进度是一个 int 值)
- progress.Report(percent);
- }
- },
- token));
- }
- private void btnCreateAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
- {
- _action = GetAsyncActionWithProgress();
- // 可以 await _action
- // IAsyncActionWithProgress<TProgress> 完成后
- _action.Completed =
- (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
- {
- // AsyncStatus 包括:Started, Completed, Canceled, Error
- lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
- };
- // IAsyncActionWithProgress<TProgress> 接收到进度后
- _action.Progress =
- (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
- {
- // 进度是一个 int 值
- lblProgress.Text = "进度: " + progressInfo.ToString();
- };
- lblMsg.Text = "开始执行";
- }
- // 取消 IAsyncActionWithProgress<TProgress>
- private void btnCancelAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
- {
- if (_action != null)
- _action.Cancel();
- }
- }
- }
4、演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
Thread/Async/IAsyncOperationWithProgressDemo.xaml
- <Page
- x:Class="XamlDemo.Thread.Async.IAsyncOperationWithProgressDemo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:XamlDemo.Thread.Async"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
- <Grid Background="Transparent">
- <StackPanel Margin="120 0 0 0">
- <TextBlock Name="lblMsg" FontSize="14.667" />
- <TextBlock Name="lblProgress" FontSize="14.667" />
- <Button Name="btnCreateAsyncOperationWithProgress" Content="执行一个 IAsyncOperationWithProgress" Click="btnCreateAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />
- <Button Name="btnCancelAsyncOperationWithProgress" Content="取消" Click="btnCancelAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />
- </StackPanel>
- </Grid>
- </Page>
Thread/Async/IAsyncOperationWithProgressDemo.xaml.cs
- /*
- * 演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
- *
- * 注:
- * 1、WinRT 中的异步功能均源自 IAsyncInfo
- * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
- *
- *
- * 另:
- * Windows.Web.Syndication.SyndicationClient.RetrieveFeedAsync() - 返回的就是 IAsyncOperationWithProgress<TResult, TProgress>
- */
- using System;
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Threading.Tasks;
- using Windows.Foundation;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- namespace XamlDemo.Thread.Async
- {
- public sealed partial class IAsyncOperationWithProgressDemo : Page
- {
- private IAsyncOperationWithProgress<string, int> _operation;
- public IAsyncOperationWithProgressDemo()
- {
- this.InitializeComponent();
- }
- private IAsyncOperationWithProgress<string, int> GetAsyncOperationWithProgress()
- {
- // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperationWithProgress<TResult, TProgress>
- return AsyncInfo.Run<string, int>(
- (token, progress) =>
- Task.Run<string>(
- () =>
- {
- // 报告进度(进度是一个 int 值)
- progress.Report();
- int percent = ;
- while (percent < )
- {
- token.WaitHandle.WaitOne();
- token.ThrowIfCancellationRequested();
- percent++;
- // 报告进度(进度是一个 int 值)
- progress.Report(percent);
- }
- // 返回结果
- return "成功了";
- },
- token));
- }
- private void btnCreateAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
- {
- _operation = GetAsyncOperationWithProgress();
- // 可以 await _operation
- // IAsyncOperationWithProgress<TResult, TProgress> 完成后
- _operation.Completed =
- (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
- {
- // AsyncStatus 包括:Started, Completed, Canceled, Error
- lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
- if (asyncStatus == AsyncStatus.Completed)
- {
- lblMsg.Text += Environment.NewLine;
- // 获取异步操作的返回结果
- lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
- }
- };
- // IAsyncOperationWithProgress<TResult, TProgress> 接收到进度后
- _operation.Progress =
- (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
- {
- // 进度是一个 int 值
- lblProgress.Text = "进度: " + progressInfo.ToString();
- };
- lblMsg.Text = "开始执行";
- }
- // 取消 IAsyncOperationWithProgress<TResult, TProgress>
- private void btnCancelAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
- {
- if (_operation != null)
- _operation.Cancel();
- }
- }
- }
OK
[源码下载]
重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress的更多相关文章
- 重新想象 Windows 8 Store Apps (44) - 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换
[源码下载] 重新想象 Windows 8 Store Apps (44) - 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换 作者:webabcd 介绍 ...
- 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法
[源码下载] 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法 作者:webabcd 介绍重新想象 Wi ...
- 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)
[源码下载] 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel) 作者:webabcd 介绍重新想象 W ...
- 重新想象 Windows 8 Store Apps (46) - 多线程之线程同步: Lock, Monitor, Interlocked, Mutex, ReaderWriterLock
[源码下载] 重新想象 Windows 8 Store Apps (46) - 多线程之线程同步: Lock, Monitor, Interlocked, Mutex, ReaderWriterLoc ...
- 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEvent, AutoResetEvent
[源码下载] 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEve ...
- 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationContext, CoreDispatcher, ThreadLocal, ThreadStaticAttribute
[源码下载] 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationCont ...
- 重新想象 Windows 8 Store Apps 系列文章索引
[源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...
- 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo
[源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...
- 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解
[源码下载] 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Toa ...
随机推荐
- spring中@param和mybatis中@param使用差别
spring中@param /** * 查询指定用户和企业关联有没有配置角色 * @param businessId memberId * @return */ int selectRoleCount ...
- Spring整合JAX-WS
Jax-ws在使用上很方便,也很轻量级.重点是他是jvnet(dev.java.net)的项目,是基于java标准的(JSR181). 不过它与Spring的整合相对麻烦,于此,我将自己的一些研究结果 ...
- Web Uploader文件上传插件
http://www.jq22.com/jquery-info2665 插件描述:WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现 ...
- 图解 Java IO : 二、FilenameFilter源码
Writer :BYSocket(泥沙砖瓦浆木匠) 微 博:BYSocket 豆 瓣:BYSocket FaceBook:BYSocket Twitter ...
- Some User Can Not Execute "Ship Confirm"(Doc ID 473312.1)
APPLIES TO: Oracle Shipping Execution - Version 11.5.10.2 and later Information in this document app ...
- Exploring Ionic Lists
Infinite Lists 由于手机不适合使用多页面显示posts,Infinite Lists成为各种新闻.咨询类app的标配.为了在ionic框架中使用到Infinite Lists,我们首先学 ...
- C 语言函数参数只能传指针,不能传数组
今天被要求编写一个C/C++冒泡算法的程序,心想这还不是手到擒来的事儿,虽然最近都是用Javascript程序,很少写C/C++程序,但是好歹也用过那么多年的C语言: 首先想的是怎么让自己的代码看上去 ...
- webkit内核分析之 Frame
参考地址:http://blog.csdn.net/dlmu2001/article/details/6164873 1. 描述 Frame类是WebCore内核同应用之间联系的一个重要的类.它 ...
- 基于jQuery点击加载动画按钮特效
分享一款基于jQuery点击加载动画按钮特效.这是一款基于jQuery+CSS3实现的鼠标点击按钮加载动画特效代码.效果图如下: 在线预览 源码下载 实现的代码. html代码: <div ...
- 菜鸟学Windows Phone 8开发(2)——了解XAML
本系列文章来源MSDN的 面向完全新手的 Windows Phone 8 开发 主要是想通过翻译本系列文章来巩固下基础知识顺带学习下英语和练习下自己的毅力 本文地址:http://channel9.m ...