C# Task异步编程

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属性。如果异步方法设置了该属性,调用方法就能获得该值并继续,否则它将暂停并等待该属性被设置,然后再继续执行。

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/429483.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

人形图案c语言程序_最多 280 字符,你能用 Basic 玩出哪些花样程序来?

(给程序员的那些事加星标)转自&#xff1a;机器之心【导读】&#xff1a;推特与计算机能擦出什么样的火花呢&#xff1f;大多数人可能就想到在计算机上发推特呗。但是&#xff0c;有人就不这么想。酷爱计算机演进史和推特的 Dominic Pajak 创建了 BBC Micro Bot&#xff0c;它能…

???--???二进制变换

题意 &#xff1a; 定义两种变换 1 &#xff1a; i i - 1 2 &#xff1a; i i - lowbit (i) 定义函数Calc(i,j)为二进制意义下 i 变换到 j 的最小步数。 给你一个二进制整数 n&#xff0c;要求 sigma {(i 1 -> n) sigma {(j 0 -> i - 1) Calc (i,j)}} 数据范围 : 令…

C# 派生类的构造函数

假定没有为任何类定义任何显式的构造函数,这样编译器就会为所有的类提供默认的初始化构 造函数,在后台会进行许多操作,但编译器可以很好地解决类的层次结构中的所有问题,每个类中 的每个字段都会初始化为对应的默认值。但在添加了一个我们自己的构造函数后,就要通过派生类 的层…

js 获取url问号前_PHP获取指定网页的HTML代码并执行输出

PHP获取指定网页的HTML代码并执行输出&#xff0c;这个方法主要是将所要或取目标的URL地址的网站中获取相关内容到自己的网页中。代码如下&#xff1a;<?php $srcurl "所要截取目标的URL地址"; $handle fopen($srcurl,"rb"); $content fread($handl…

AD16画线时如何切换90°、45°、任意角度画线模式

在绘图界面选择画线后&#xff0c;使用“shift空格”可切换不同的画线模式。切换过程中会有90模式、45度模式、任意角度模式等&#xff0c;在这些模式中可使用空格键在进行细分切换。 1、90模式 2、45模式 3、任意模式

1200兆路由器网速_如何选购路由器才能发挥宽带的网速?

很多人多少都会遇到家里宽带网速慢的时候&#xff0c;家中明明是光纤宽带&#xff0c;可是网速却没有想象中的那么快&#xff1f;尤其是宽带的带宽升级到100M、200M、500M的时候&#xff0c;感觉跟没有提速一样。也许你家的路由器该换新啦&#xff01;那么&#xff0c;想要选购…

C# 静态类

------《C#高级编程》第7版

学习曾国藩,学做人做事学技术

三个字&#xff1a;诚、勤、恒早期&#xff1a; 早起、耐烦、有恒 语录&#xff1a;不日进&#xff0c;就日退 语录&#xff1a;拙看似慢&#xff0c;实则最快&#xff01; &#xff08;反思学技术&#xff1f;&#xff09; 语录&#xff1a; 决定成败的&#xff0c;不在高处…

vant实现下拉刷新和上拉加载_微信小程序 - 实现下拉刷新、上拉加载

在小程序开发中使用下拉刷新和上拉加载非常多&#xff0c;比如常用的展示型首页&#xff0c;而实现这个功能有两种形式&#xff0c;第一种是使用 scroll-view 组件&#xff0c;第二种是不使用 scroll-view 组件而让整个页面刷新&#xff0c;那就分别都在此简单分享下。方法一在…

经验证过的跨线程更新辅助类MyInvokeHelper

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Windows.Forms;namespace Extension.MyDll {/// <summary>/// 辅助类&#xff1a;跨线程更新控件/// &l…

02函数-03-闭包

1、闭包的概念闭包是一种特殊的程序结构&#xff0c;即 函数A中定义了另一个函数a&#xff0c;内部函数a引用了外部函数A的参数和局部变量&#xff0c;最终A会返回一个保存了相关参数和变量的函数a。简洁地说&#xff0c;外层函数将保存了信息的可执行内层函数作为结果返回。来…

mapper同时添加数据只能添加一条_springcloud项目搭建第二节:eureka+数据库

在上一节搭建的项目基础上&#xff0c;在父项目spring-cloud的pom文件中添加mapper启动器和mysql驱动的配置&#xff0c;如果项目中使用lombok也可以引用&#xff0c;这里需要注意的是lombok引用的配置不在dependencyManagement结构中&#xff0c;这时为什么呢&#xff0c;因为…

C#控件命名规范

类 型 前 缀 示 例 Adrotator adrt adrtTopAd BulletedList blst blstCity Button btn btnSubmit Calendar cal calMettingDates CheckBox chk chkBlue CheckBoxList chkl chklFavColors DropDownList drop dropCountries FileUpLoad fup fupImage …

在centOS7.2里安装virtualenv和flask

1&#xff09; 安装pip工具 #wget https://bootstrap.pypa.io/get-pip.py #python get-pip.py 2&#xff09; 安装virtualenv&#xff0c;并创建一个开发环境 #pip install virtualenv #mkdir rongtangzi #创建一个项目 #cd rongtangzi #virtualenv env1 #…

事务连接中断_一文搞懂分布式事务-CAP理论

互联网系统中&#xff0c;分布式事务是无法避免的&#xff0c;目前多数解决方案是BASE理论&#xff0c;最终一致性&#xff0c;结合事务补偿。1.什么是CAP理论。CAP理论&#xff0c;又称为布鲁尔定理&#xff0c;是加州大学伯克利分校的计算机科学家埃里克.布鲁尔(Eric Brewer)…

C# WinForm中获取当前程序运行目录的方法

C# WinForm中获取当前程序运行目录的方法&#xff1a; “AppDomain.CurrentDomain.BaseDirectory”:获取当前应用程序所在目录的路径&#xff0c;最后包含“\”&#xff1b;“System.Threading.Thread.GetDomain().BaseDirectory”:获取当前应用程序所在目录的路径&#xff0c…

网络攻防 第四周学习总结

教材学习内容总结 第四章主要介绍了网络嗅探和协议分析网络嗅探是一种常用的窃听技术&#xff0c;它利用计算机的网络接口截获目的地为其他计算机的数据报文&#xff0c;以监听数据流中所包含的用户账户密码或私密信息等。 网络嗅探具有很强的隐蔽性&#xff0c;往往让网络信息…

获取内存_如何获取一个进程所占用的内存

推荐观看&#xff1a;BATJ面试官最喜欢问的&#xff1a;多线程、线程并发面试题详解&#xff08;volatileThreadLocalSleep&#xff09;_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili​www.bilibili.com通过 ps 可以获知一个进程所占用的内存$ ps -O rss -p 3506PID RSS S TTY …

461. Hamming Distance【数学|位运算】

2017/3/14 15:23:55 The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. 题目要求&#xff1a;求两个数字二进制位中同一位置不同bit的个数…

中的ama格式_想发SCI?期刊引用格式选好了没?

我~芳~老师~又回来开坑了哈哈哈哈哈&#xff01;&#xff01;&#xff01;对于一心想要冲向SCI、EI顶峰&#xff0c;拉都拉不住的同学来说&#xff0c;我们需要把论文中的每一个细节都抠得死死的。合乎规范地引用科学期刊&#xff08;Scientific Journal&#xff09;绝对是最重…