1、不适用异步的示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Diagnostics;namespace ConsoleApplication1
{class MyDownloadString{Stopwatch sw = new Stopwatch();private int CountCharacters(int id, string uriString){WebClient wc1 = new WebClient();Console.WriteLine("Starting call {0}     :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);string result = wc1.DownloadString(new Uri(uriString));Console.WriteLine("   Call {0} completed :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);return result.Length;}private void CountToALargeNumber(int id, int value){for (long i = 0; i < value; i++){}Console.WriteLine("   End counting  {0}  :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);}public void DoRun(){const int largeNumber = 6000000;const string microsoft = "http://www.microsoft.com";const string baidu = "http://www.baidu.com";sw.Start();int t1 = CountCharacters(1, microsoft);int t2 = CountCharacters(2, baidu);CountToALargeNumber(1, largeNumber);CountToALargeNumber(2, largeNumber);CountToALargeNumber(3, largeNumber);CountToALargeNumber(4, largeNumber);Console.WriteLine("Chars in {0}    :{1}", microsoft, t1);Console.WriteLine("Chars in {0}        :{1}", baidu, t2);}}class Program{static void Main(string[] args){MyDownloadString mds = new MyDownloadString();mds.DoRun();}}}

运行结果:

2、使用异步的示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Diagnostics;namespace ConsoleApplication1
{class MyDownloadString{Stopwatch sw = new Stopwatch();private async Task<int> CountCharactersAsyc(int id, string uriString){WebClient wc1 = new WebClient();Console.WriteLine("Starting call {0}     :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);string result = await wc1.DownloadStringTaskAsync(new Uri(uriString));Console.WriteLine("   Call {0} completed :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);return result.Length;}private void CountToALargeNumber(int id, int value){for (long i = 0; i < value; i++){}Console.WriteLine("   End counting  {0}  :    {1, 4:N0} ms", id, sw.Elapsed.TotalMilliseconds);}public void DoRun(){const int largeNumber = 6000000;const string microsoft = "http://www.microsoft.com";const string baidu = "http://www.baidu.com";sw.Start();Task<int> t1 = CountCharactersAsyc(1, microsoft);Task<int> t2 = CountCharactersAsyc(2, baidu);CountToALargeNumber(1, largeNumber);CountToALargeNumber(2, largeNumber);CountToALargeNumber(3, largeNumber);CountToALargeNumber(4, largeNumber);Console.WriteLine("Chars in {0}    :{1}", microsoft, t1.Result);Console.WriteLine("Chars in {0}        :{1}", baidu, t1.Result);}}class Program{static void Main(string[] args){MyDownloadString mds = new MyDownloadString();mds.DoRun();}}}

运行结果:

3、使用返回Task<int>对象的异步方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Diagnostics;namespace ConsoleApplication1
{static class DoAsyncStuff{private static int GetSum(int i1, int i2){Thread.Sleep(3000);return i1 + i2;}public static async Task<int> CalculateSumAsync(int i1, int i2){int sum = await Task.Run(() => GetSum(i1, i2));return sum;}}class Program{static void Main(string[] args){Stopwatch sw = new Stopwatch();ConsoleColor color = Console.ForegroundColor;sw.Start();int a1 = 5;int a2 = 6;int a3 = 2;int a4 = 3;Task<int> value = DoAsyncStuff.CalculateSumAsync(a1, a2);Task<int> value2 = DoAsyncStuff.CalculateSumAsync(a3, a4);Console.WriteLine("1)Starting... {0}ms", sw.Elapsed.TotalMilliseconds);Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine("1)Result:[ {0}+{1}={2} ]", a1, a2, value.Result);Console.ForegroundColor = color;Console.WriteLine("1)Ended!      {0}ms", sw.Elapsed.TotalMilliseconds);Console.WriteLine("2)Starting... {0}ms", sw.Elapsed.TotalMilliseconds);Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine("2)Result:[ {0}+{1}={2} ]", a3, a4, value2.Result);Console.ForegroundColor = color;Console.WriteLine("2)Ended!      {0}ms", sw.Elapsed.TotalMilliseconds);sw.Stop();}}}

运行结果:

以上程序实际上在两个DoAsyncStuff.CalculateSumAsync异步方法中分别执行a1+a2和a3+a4的运算,调用方法即Main方法中的代码将继续其进程,从异步方法中获取Task<int>的对象。当需要实际值时,就引用Task对象的Result属性。如果异步方法设置了该属性,调用方法就能获得该值并继续,否则它将暂停并等待该属性被设置,然后再继续执行。

C# Task异步编程相关推荐

  1. .NET 4.5 Task异步编程学习资料

    参考资料: 1. http://www.cnblogs.com/heyuquan/archive/2013/04/18/3028044.html 转载于:https://www.cnblogs.com ...

  2. 【转】异步编程系列(Thread、Task、async/await、ajax等)

    序 经过一番努力,我写的异步编程系列也算有头有尾,当然不是说这个系列已经更新完毕,这个头尾只是表示新旧知识点都有简单涉及到,接下去我还会丰富这一系列并且有机会整个小应用(愿景是弄一个开源组件吧,结合s ...

  3. .NET异步编程之新利器——Task与Await、Async

    一.  FrameWork 4.0之前的线程世界    在.NET FrameWork 4.0之前,如果我们使用线程.一般有以下几种方式: 使用System.Threading.Thread 类,调用 ...

  4. C++ concurrency::task实现异步编程(Windows)

    最近一直在看js.python.lua等脚本语言的异步编程,今天脑子一热突然想看看C++能否也有支持异步的相关类库,上网一搜还真的有 microsoft官方文档https://msdn.microso ...

  5. 使用 Task 简化异步编程

    .Net 传统异步编程概述 .NET Framework 提供以下两种执行 I/O 绑定和计算绑定异步操作的标准模式: 异步编程模型 (APM),在该模型中异步操作由一对 Begin/End 方法(如 ...

  6. @async 默认线程池_.NET Web应用中为什么要使用async/await异步编程?

    布莱恩特:.NET Core开发精选文章目录,持续更新,欢迎投稿!​zhuanlan.zhihu.com 前言 1.什么是async/await? await和async是.NET Framework ...

  7. java 如何只暴露接口_Java并发异步编程,原来十个接口的活现在只需要一个接口就搞定...

    什么?对你没有听错,也没有看错 ..多线程并发执行任务,取结果归集~~ 不再忧愁-. 引言 先来看一些APP的获取数据,诸如此类,一个页面获取N多个,多达10个左右的一个用户行为数据,比如:点赞数,发 ...

  8. Atitit. Async await 优缺点 异步编程的原理and实现 java c# php

    Atitit. Async await 优缺点 异步编程的原理and实现 java c# php 1. async & await的来源1 2. 异步编程history1 2.1. 线程池 2 ...

  9. C#:异步编程和线程的使用(.NET 4.5 ),异步方法改为同步执行

    摘自:http://www.codeproject.com/Articles/996857/Asynchronous-programming-and-Threading-in-Csharp-N(葡萄城 ...

最新文章

  1. SAP QM 检验批上留样记录如何看?
  2. 如何解析属性文件(properties)获取键值对的值?
  3. 最大公约数(Greatest Common Divisor)
  4. C语言强化——学生管理系统
  5. listview选中高亮
  6. datagridview输入数据格式化_第五节,输入输出函数
  7. request模块发送json请求
  8. Voxel-Based Global Illumination
  9. Win10命令提示符在哪里 怎么打开命令提示符窗口
  10. Qy词典-免费离线的中英词典
  11. python:实现使用分而治之找到单峰列表的峰值算法(附完整源码)
  12. 计算机考研专业课408备考经验分享
  13. word文档单独删除或修改首页或某一页的页眉页脚及其下划线
  14. Firefox主页被360篡改该怎么办
  15. 打开新材料世界的大门:拓扑电子材料目录问世
  16. yolo实现交通信号灯视频流识别代码搬运及调试
  17. 程序员的“三十而已”
  18. disallow php,在robots.txt中Disallow: /abc和Disallow: /abc/的区别
  19. 2021年9月PMP考试新鲜出炉,如何查询成绩?
  20. [Crypto]ECB模式攻击

热门文章

  1. java通用分页条件查询_通用分页查询
  2. HTTP和HTTPS协议及工作原理分析
  3. 项目集成Spring Security
  4. ftp 530 linux,Linux启动ftp服务器530 Permission denied解决方法
  5. 申请鲲鹏920测试机试水+编译nginx
  6. LeetCode刷题过程中的一些小tips
  7. 湖南师大计算机学院院长,董新汉(数学与计算机科学学院)老师 - 湖南师范大学 - 院校大全...
  8. 输入字符串统计字符串中每个字符出现的次数
  9. 1083. List Grades (25)
  10. pg高性能服务器,Pgpool-II 负载均衡对PG的性能影响