[源码下载]

重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress

作者:webabcd

介绍
重新想象 Windows 8 Store Apps 之 异步编程

  • IAsyncAction - 无返回值,无进度值
  • IAsyncOperation - 有返回值,无进度值
  • IAsyncActionWithProgress - 无返回值,有进度值
  • IAsyncOperationWithProgress - 有返回值,有进度值

示例
1、演示 IAsyncAction(无返回值,无进度值)的用法
Thread/Async/IAsyncActionDemo.xaml

  1. <Page
  2. x:Class="XamlDemo.Thread.Async.IAsyncActionDemo"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Thread.Async"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <TextBlock Name="lblMsg" FontSize="14.667" />
  14.  
  15. <Button Name="btnCreateAsyncAction" Content="执行一个 IAsyncAction" Click="btnCreateAsyncAction_Click_1" Margin="0 10 0 0" />
  16.  
  17. <Button Name="btnCancelAsyncAction" Content="取消" Click="btnCancelAsyncAction_Click_1" Margin="0 10 0 0" />
  18.  
  19. </StackPanel>
  20. </Grid>
  21. </Page>

Thread/Async/IAsyncActionDemo.xaml.cs

  1. /*
  2. * 演示 IAsyncAction(无返回值,无进度值)的用法
  3. *
  4. * 注:
  5. * 1、WinRT 中的异步功能均源自 IAsyncInfo
  6. * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
  7. *
  8. *
  9. * 另:
  10. * Windows.System.Threading.ThreadPool.RunAsync() - 返回的就是 IAsyncAction
  11. */
  12.  
  13. using System.Runtime.InteropServices.WindowsRuntime;
  14. using System.Threading.Tasks;
  15. using Windows.Foundation;
  16. using Windows.UI.Xaml;
  17. using Windows.UI.Xaml.Controls;
  18.  
  19. namespace XamlDemo.Thread.Async
  20. {
  21. public sealed partial class IAsyncActionDemo : Page
  22. {
  23. private IAsyncAction _action;
  24.  
  25. public IAsyncActionDemo()
  26. {
  27. this.InitializeComponent();
  28. }
  29.  
  30. private IAsyncAction GetAsyncAction()
  31. {
  32. // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncAction
  33. return AsyncInfo.Run(
  34. (token) => // CancellationToken token
  35. Task.Run(
  36. () =>
  37. {
  38. token.WaitHandle.WaitOne();
  39. token.ThrowIfCancellationRequested();
  40. },
  41. token));
  42. }
  43.  
  44. private void btnCreateAsyncAction_Click_1(object sender, RoutedEventArgs e)
  45. {
  46. _action = GetAsyncAction();
  47.  
  48. // 可以 await _action
  49.  
  50. // IAsyncAction 完成后
  51. _action.Completed =
  52. (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
  53. {
  54. // AsyncStatus 包括:Started, Completed, Canceled, Error
  55. lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
  56. };
  57.  
  58. lblMsg.Text = "开始执行,3 秒后完成";
  59. }
  60.  
  61. // 取消 IAsyncAction
  62. private void btnCancelAsyncAction_Click_1(object sender, RoutedEventArgs e)
  63. {
  64. if (_action != null)
  65. _action.Cancel();
  66. }
  67. }
  68. }

2、演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
Thread/Async/IAsyncOperationDemo.xaml

  1. <Page
  2. x:Class="XamlDemo.Thread.Async.IAsyncOperationDemo"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Thread.Async"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <TextBlock Name="lblMsg" FontSize="14.667" />
  14.  
  15. <Button Name="btnCreateAsyncOperation" Content="执行一个 IAsyncOperation" Click="btnCreateAsyncOperation_Click_1" Margin="0 10 0 0" />
  16.  
  17. <Button Name="btnCancelAsyncOperation" Content="取消" Click="btnCancelAsyncOperation_Click_1" Margin="0 10 0 0" />
  18.  
  19. </StackPanel>
  20. </Grid>
  21. </Page>

Thread/Async/IAsyncOperationDemo.xaml.cs

  1. /*
  2. * 演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
  3. *
  4. * 注:
  5. * 1、WinRT 中的异步功能均源自 IAsyncInfo
  6. * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
  7. */
  8.  
  9. using System;
  10. using System.Runtime.InteropServices.WindowsRuntime;
  11. using System.Threading.Tasks;
  12. using Windows.Foundation;
  13. using Windows.UI.Xaml;
  14. using Windows.UI.Xaml.Controls;
  15.  
  16. namespace XamlDemo.Thread.Async
  17. {
  18. public sealed partial class IAsyncOperationDemo : Page
  19. {
  20. private IAsyncOperation<int> _operation;
  21.  
  22. public IAsyncOperationDemo()
  23. {
  24. this.InitializeComponent();
  25. }
  26.  
  27. private IAsyncOperation<int> GetAsyncOperation(int x, int y)
  28. {
  29. // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperation<TResult>
  30. return AsyncInfo.Run<int>(
  31. (token) => // CancellationToken token
  32. Task.Run<int>(
  33. () =>
  34. {
  35. token.WaitHandle.WaitOne();
  36. token.ThrowIfCancellationRequested();
  37.  
  38. // 返回结果
  39. return x * y;
  40. },
  41. token));
  42. }
  43.  
  44. private void btnCreateAsyncOperation_Click_1(object sender, RoutedEventArgs e)
  45. {
  46. _operation = GetAsyncOperation(, );
  47.  
  48. // 可以 await _operation
  49.  
  50. // IAsyncOperation<TResult> 完成后
  51. _operation.Completed =
  52. (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
  53. {
  54. // AsyncStatus 包括:Started, Completed, Canceled, Error
  55. lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
  56.  
  57. if (asyncStatus == AsyncStatus.Completed)
  58. {
  59. lblMsg.Text += Environment.NewLine;
  60. // 获取异步操作的返回结果
  61. lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
  62. }
  63. };
  64.  
  65. lblMsg.Text = "开始执行,3 秒后完成";
  66. }
  67.  
  68. // 取消 IAsyncOperation<TResult>
  69. private void btnCancelAsyncOperation_Click_1(object sender, RoutedEventArgs e)
  70. {
  71. if (_operation != null)
  72. _operation.Cancel();
  73. }
  74. }
  75. }

3、演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
Thread/Async/IAsyncActionWithProgressDemo.xaml

  1. <Page
  2. x:Class="XamlDemo.Thread.Async.IAsyncActionWithProgressDemo"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Thread.Async"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <TextBlock Name="lblMsg" FontSize="14.667" />
  14. <TextBlock Name="lblProgress" FontSize="14.667" />
  15.  
  16. <Button Name="btnCreateAsyncActionWithProgress" Content="执行一个 IAsyncActionWithProgress" Click="btnCreateAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />
  17.  
  18. <Button Name="btnCancelAsyncActionWithProgress" Content="取消" Click="btnCancelAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />
  19.  
  20. </StackPanel>
  21. </Grid>
  22. </Page>

Thread/Async/IAsyncActionWithProgressDemo.xaml.cs

  1. /*
  2. * 演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
  3. *
  4. * 注:
  5. * 1、WinRT 中的异步功能均源自 IAsyncInfo
  6. * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
  7. */
  8.  
  9. using System.Runtime.InteropServices.WindowsRuntime;
  10. using System.Threading.Tasks;
  11. using Windows.Foundation;
  12. using Windows.UI.Xaml;
  13. using Windows.UI.Xaml.Controls;
  14.  
  15. namespace XamlDemo.Thread.Async
  16. {
  17. public sealed partial class IAsyncActionWithProgressDemo : Page
  18. {
  19. private IAsyncActionWithProgress<int> _action;
  20.  
  21. public IAsyncActionWithProgressDemo()
  22. {
  23. this.InitializeComponent();
  24. }
  25.  
  26. private IAsyncActionWithProgress<int> GetAsyncActionWithProgress()
  27. {
  28. // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncActionWithProgress<TProgress>
  29. return AsyncInfo.Run<int>(
  30. (token, progress) => // CancellationToken token, IProgress<TProgress> progress
  31. Task.Run(
  32. () =>
  33. {
  34. // 报告进度(进度是一个 int 值)
  35. progress.Report();
  36.  
  37. int percent = ;
  38. while (percent < )
  39. {
  40. token.WaitHandle.WaitOne();
  41. token.ThrowIfCancellationRequested();
  42.  
  43. percent++;
  44.  
  45. // 报告进度(进度是一个 int 值)
  46. progress.Report(percent);
  47. }
  48. },
  49. token));
  50. }
  51.  
  52. private void btnCreateAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
  53. {
  54. _action = GetAsyncActionWithProgress();
  55.  
  56. // 可以 await _action
  57.  
  58. // IAsyncActionWithProgress<TProgress> 完成后
  59. _action.Completed =
  60. (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
  61. {
  62. // AsyncStatus 包括:Started, Completed, Canceled, Error
  63. lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
  64. };
  65.  
  66. // IAsyncActionWithProgress<TProgress> 接收到进度后
  67. _action.Progress =
  68. (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
  69. {
  70. // 进度是一个 int 值
  71. lblProgress.Text = "进度: " + progressInfo.ToString();
  72. };
  73.  
  74. lblMsg.Text = "开始执行";
  75. }
  76.  
  77. // 取消 IAsyncActionWithProgress<TProgress>
  78. private void btnCancelAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
  79. {
  80. if (_action != null)
  81. _action.Cancel();
  82. }
  83. }
  84. }

4、演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
Thread/Async/IAsyncOperationWithProgressDemo.xaml

  1. <Page
  2. x:Class="XamlDemo.Thread.Async.IAsyncOperationWithProgressDemo"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Thread.Async"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <TextBlock Name="lblMsg" FontSize="14.667" />
  14. <TextBlock Name="lblProgress" FontSize="14.667" />
  15.  
  16. <Button Name="btnCreateAsyncOperationWithProgress" Content="执行一个 IAsyncOperationWithProgress" Click="btnCreateAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />
  17.  
  18. <Button Name="btnCancelAsyncOperationWithProgress" Content="取消" Click="btnCancelAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />
  19.  
  20. </StackPanel>
  21. </Grid>
  22. </Page>

Thread/Async/IAsyncOperationWithProgressDemo.xaml.cs

  1. /*
  2. * 演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
  3. *
  4. * 注:
  5. * 1、WinRT 中的异步功能均源自 IAsyncInfo
  6. * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
  7. *
  8. *
  9. * 另:
  10. * Windows.Web.Syndication.SyndicationClient.RetrieveFeedAsync() - 返回的就是 IAsyncOperationWithProgress<TResult, TProgress>
  11. */
  12.  
  13. using System;
  14. using System.Runtime.InteropServices.WindowsRuntime;
  15. using System.Threading.Tasks;
  16. using Windows.Foundation;
  17. using Windows.UI.Xaml;
  18. using Windows.UI.Xaml.Controls;
  19.  
  20. namespace XamlDemo.Thread.Async
  21. {
  22. public sealed partial class IAsyncOperationWithProgressDemo : Page
  23. {
  24. private IAsyncOperationWithProgress<string, int> _operation;
  25.  
  26. public IAsyncOperationWithProgressDemo()
  27. {
  28. this.InitializeComponent();
  29. }
  30.  
  31. private IAsyncOperationWithProgress<string, int> GetAsyncOperationWithProgress()
  32. {
  33. // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperationWithProgress<TResult, TProgress>
  34. return AsyncInfo.Run<string, int>(
  35. (token, progress) =>
  36. Task.Run<string>(
  37. () =>
  38. {
  39. // 报告进度(进度是一个 int 值)
  40. progress.Report();
  41.  
  42. int percent = ;
  43. while (percent < )
  44. {
  45. token.WaitHandle.WaitOne();
  46. token.ThrowIfCancellationRequested();
  47.  
  48. percent++;
  49.  
  50. // 报告进度(进度是一个 int 值)
  51. progress.Report(percent);
  52. }
  53.  
  54. // 返回结果
  55. return "成功了";
  56. },
  57. token));
  58. }
  59.  
  60. private void btnCreateAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
  61. {
  62. _operation = GetAsyncOperationWithProgress();
  63.  
  64. // 可以 await _operation
  65.  
  66. // IAsyncOperationWithProgress<TResult, TProgress> 完成后
  67. _operation.Completed =
  68. (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
  69. {
  70. // AsyncStatus 包括:Started, Completed, Canceled, Error
  71. lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
  72.  
  73. if (asyncStatus == AsyncStatus.Completed)
  74. {
  75. lblMsg.Text += Environment.NewLine;
  76. // 获取异步操作的返回结果
  77. lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
  78. }
  79. };
  80.  
  81. // IAsyncOperationWithProgress<TResult, TProgress> 接收到进度后
  82. _operation.Progress =
  83. (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
  84. {
  85. // 进度是一个 int 值
  86. lblProgress.Text = "进度: " + progressInfo.ToString();
  87. };
  88.  
  89. lblMsg.Text = "开始执行";
  90. }
  91.  
  92. // 取消 IAsyncOperationWithProgress<TResult, TProgress>
  93. private void btnCancelAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
  94. {
  95. if (_operation != null)
  96. _operation.Cancel();
  97. }
  98. }
  99. }

OK
[源码下载]

重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress的更多相关文章

  1. 重新想象 Windows 8 Store Apps (44) - 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换

    [源码下载] 重新想象 Windows 8 Store Apps (44) - 多线程之异步编程: 经典和最新的异步编程模型, IAsyncInfo 与 Task 相互转换 作者:webabcd 介绍 ...

  2. 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法

    [源码下载] 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法 作者:webabcd 介绍重新想象 Wi ...

  3. 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)

    [源码下载] 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel) 作者:webabcd 介绍重新想象 W ...

  4. 重新想象 Windows 8 Store Apps (46) - 多线程之线程同步: Lock, Monitor, Interlocked, Mutex, ReaderWriterLock

    [源码下载] 重新想象 Windows 8 Store Apps (46) - 多线程之线程同步: Lock, Monitor, Interlocked, Mutex, ReaderWriterLoc ...

  5. 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEvent, AutoResetEvent

    [源码下载] 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEve ...

  6. 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationContext, CoreDispatcher, ThreadLocal, ThreadStaticAttribute

    [源码下载] 重新想象 Windows 8 Store Apps (48) - 多线程之其他辅助类: SpinWait, SpinLock, Volatile, SynchronizationCont ...

  7. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  8. 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

    [源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...

  9. 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解

    [源码下载] 重新想象 Windows 8 Store Apps (35) - 通知: Toast 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Toa ...

随机推荐

  1. spring中@param和mybatis中@param使用差别

    spring中@param /** * 查询指定用户和企业关联有没有配置角色 * @param businessId memberId * @return */ int selectRoleCount ...

  2. Spring整合JAX-WS

    Jax-ws在使用上很方便,也很轻量级.重点是他是jvnet(dev.java.net)的项目,是基于java标准的(JSR181). 不过它与Spring的整合相对麻烦,于此,我将自己的一些研究结果 ...

  3. Web Uploader文件上传插件

    http://www.jq22.com/jquery-info2665   插件描述:WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现 ...

  4. 图解 Java IO : 二、FilenameFilter源码

    Writer      :BYSocket(泥沙砖瓦浆木匠) 微         博:BYSocket 豆         瓣:BYSocket FaceBook:BYSocket Twitter   ...

  5. 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 ...

  6. Exploring Ionic Lists

    Infinite Lists 由于手机不适合使用多页面显示posts,Infinite Lists成为各种新闻.咨询类app的标配.为了在ionic框架中使用到Infinite Lists,我们首先学 ...

  7. C 语言函数参数只能传指针,不能传数组

    今天被要求编写一个C/C++冒泡算法的程序,心想这还不是手到擒来的事儿,虽然最近都是用Javascript程序,很少写C/C++程序,但是好歹也用过那么多年的C语言: 首先想的是怎么让自己的代码看上去 ...

  8. webkit内核分析之 Frame

    参考地址:http://blog.csdn.net/dlmu2001/article/details/6164873 1.    描述 Frame类是WebCore内核同应用之间联系的一个重要的类.它 ...

  9. 基于jQuery点击加载动画按钮特效

    分享一款基于jQuery点击加载动画按钮特效.这是一款基于jQuery+CSS3实现的鼠标点击按钮加载动画特效代码.效果图如下: 在线预览   源码下载 实现的代码. html代码: <div ...

  10. 菜鸟学Windows Phone 8开发(2)——了解XAML

    本系列文章来源MSDN的 面向完全新手的 Windows Phone 8 开发 主要是想通过翻译本系列文章来巩固下基础知识顺带学习下英语和练习下自己的毅力 本文地址:http://channel9.m ...