重新想象 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 ...
 
随机推荐
- Oracle 一次生产分库,升级,迁移
			
今天完成了一个负载较高的中央数据库的分库操作, 并实现了oracle的滚动升级(10.2.0.1->10.2.0.4), 业务中断仅15分钟. 平台: RHEL AS 4 + Oracle 10 ...
 - PowerShell定时记录操作系统行为
			
作为系统管理员,有些时候是需要记录系统中的其他用户的一些操作行为的,例如:当系统管理员怀疑系统存在漏洞,且已经有被植入后门或者创建隐藏账户时,就需要对曾经登陆的用户进行监控,保存其打开或者操作过的文件 ...
 - 关于php的mysqlnd驱动
			
1.什么是mysqlnd驱动? PHP手册上的描述: MySQL Native Driver is a replacement for the MySQL Client Library (libmys ...
 - 多条件动态LINQ 组合查询
			
本文章转载:http://www.cnblogs.com/wangiqngpei557/archive/2013/02/05/2893096.html 参考:http://dotnet.9sssd.c ...
 - Firefox火狐添加书签功能失灵解决办法
			
一直使用firefox,书签管理用的是插件Tabmix.感觉很好,只是不知道从那天起添加书签就不灵了!不论是Ctrl+D快捷键,还是Add Bookmark Here2插件,甚至“将此页加为书签”的菜 ...
 - iOS开发之时间格式的转化
			
在开发iOS程序时,有时候需要将时间格式调整成自己希望的格式,这个时候我们可以用NSDateFormatter类来处理. 例如:如何将格式为“12-May-14 05.08.02.000000 PM” ...
 - system 函数
			
相关函数:fork, execve, waitpid, popen 头文件:#include <stdlib.h> 定义函数:int system(const char * string) ...
 - viewWithTag获取subview规则详解
			
通常我们在view层级里面对subView的操作可以通过两种方式:1.保留一个subview的引用,然后在类中通过该引用对该subview进行操作,但是要注意在适当的位置添加内存维护的代码,退出前手动 ...
 - Android样式的开发:layer-list篇
			
上图Tab的背景效果,和带阴影的圆角矩形,是怎么实现的呢?大部分的人会让美工切图,用点九图做背景.但是,如果只提供一张图,会怎么样呢?比如,中间的Tab背景红色底线的像素高度为4px,那么,在mdpi ...
 - SQL Server 2008 Windows身份验证改为混合模式身份验证
			
1.在当前服务器右键进入“属性页”->“安全性”->勾选Sql Server和Windows身份验证模式->确定. 由于默认不启用sa,所以如果启用sa账户登录,则还需要如下设置: ...