1. //filename: MathOperations.cs
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace TestAsyncAwait
  9. {
  10. public class MathOperations
  11. {
  12. public static double MultiplyByTwo(double d)
  13. {
  14. return d * 2;
  15. }
  16.  
  17. public static double Square(double d)
  18. {
  19. return d * d;
  20. }
  21.  
  22. }
  23. }
  24.  
  25. //filename: MyClass.cs
  26. using System;
  27. using System.Collections.Generic;
  28. using System.Linq;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32.  
  33. namespace TestAsyncAwait
  34. {
  35. public class MyClass
  36. {
  37. public MyClass()
  38. {
  39. //DisplayValue();
  40. DisplayValueWithContinuationTask();
  41. Console.WriteLine("MyClass() end.");
  42. }
  43.  
  44. public Task<double> GetValueAsync(double num1, double num2)
  45. {
  46. return Task.Run<double>(() => {
  47. Thread.Sleep(1000);
  48. return num1 + num2;
  49. });
  50. }
  51.  
  52. public async void DisplayValue()
  53. {
  54. double result = await GetValueAsync(1, 2);
  55. Console.WriteLine("result is :" + result);
  56. }
  57.  
  58. public void DisplayValueWithContinuationTask()
  59. {
  60. Task<double> task = GetValueAsync(1, 2);
  61. task.ContinueWith(t =>
  62. {
  63. double result = t.Result;
  64. Console.WriteLine("result is :" + result);
  65. });
  66. }
  67.  
  68. }
  69. }
  70.  
  71. //filename: Program.cs
  72. using System;
  73. using System.Collections.Generic;
  74. using System.Linq;
  75. using System.Text;
  76. using System.Threading;
  77. using System.Threading.Tasks;
  78.  
  79. namespace TestAsyncAwait
  80. {
  81. class Program
  82. {
  83. public static Tuple<int, int> Divide(int dividend, int divisor)
  84. {
  85. int result = dividend / divisor;
  86. int reminder = dividend % divisor;
  87. return Tuple.Create<int, int>(result, reminder);
  88. }
  89.  
  90. private delegate string GetAString();
  91.  
  92. static void ProcessAndDispalyNumber(Func<double,double> action, double value){
  93. double result = action(value);
  94. Console.WriteLine(string.Format("value={0},result={1}", value, result));
  95. }
  96.  
  97. #region 异步编程实验
  98.  
  99. static string Greeting(string name)
  100. {
  101. Thread.Sleep(3000);
  102. return string.Format("threadID:[{0}] says: Hello, {1}!", Thread.CurrentThread.ManagedThreadId, name);
  103. }
  104.  
  105. static Task<string> GreetingAsync(string name)
  106. {
  107. return Task.Run<string>(() => {
  108. return Greeting(name);
  109. });
  110. }
  111.  
  112. async static void CallerWithAsync()
  113. {
  114. string result = await GreetingAsync("张三");
  115. Console.WriteLine(result);
  116. }
  117.  
  118. static void CallerWithContinuationWith()
  119. {
  120. Task<string> task = GreetingAsync("张三");
  121. task.ContinueWith(t => {
  122. string result = t.Result;
  123. Console.WriteLine(result);
  124. });
  125. }
  126.  
  127. async static void MultipleAsyncMethods()
  128. {
  129. string result1 = await GreetingAsync("张三@");
  130. string result2 = await GreetingAsync("李四@");
  131. Console.WriteLine("Finished with 2 result: {0},{1}", result1, result2);
  132. }
  133.  
  134. async static void MultipleAsyncMethodsWithCombinators1()
  135. {
  136. Task<string> t1 = GreetingAsync("张三1");
  137. Task<string> t2 = GreetingAsync("李四1");
  138. await Task.WhenAll(t1, t2);
  139. Console.WriteLine("Finished with 2 result: {0},{1}", t1.Result, t2.Result);
  140. }
  141.  
  142. async static void MultipleAsyncMethodsWithCombinators2()
  143. {
  144. Task<string> t1 = GreetingAsync("张三2");
  145. Task<string> t2 = GreetingAsync("李四2");
  146. string[] result = await Task.WhenAll(t1, t2);
  147. Console.WriteLine("Finished with 2 result: {0},{1}", result[0], result[1]);
  148. }
  149.  
  150. #endregion
  151.  
  152. static void Main(string[] args)
  153. {
  154. /*
  155. CallerWithAsync();
  156. CallerWithContinuationWith();
  157. MultipleAsyncMethods();
  158. MultipleAsyncMethodsWithCombinators1();
  159. MultipleAsyncMethodsWithCombinators2();
  160.  
  161. Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Done.");
  162. */
  163. ParallelLoopResult result = Parallel.For(0, 10, async i => {
  164. Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId,
  165. Thread.CurrentThread.ManagedThreadId);
  166. //Thread.Sleep(10);
  167. await Task.Delay(10);
  168. Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId,
  169. Thread.CurrentThread.ManagedThreadId);
  170. });
  171. Console.WriteLine("Is completed: {0}", result.IsCompleted);
  172.  
  173. /*
  174. MyClass mc = new MyClass();
  175.  
  176. Console.WriteLine("-----------------");
  177.  
  178. var result = Divide(5, 2);
  179. Console.WriteLine(string.Format("result={0},reminder={1}",result.Item1, result.Item2));
  180.  
  181. int x = 4;
  182. //GetAString func = new GetAString(x.ToString);
  183. GetAString func = x.ToString;
  184. Console.WriteLine(func());
  185. Console.WriteLine(func.Invoke());
  186.  
  187. Func<double, double>[] operations =
  188. {
  189. MathOperations.MultiplyByTwo,
  190. MathOperations.Square
  191. };
  192. foreach (var item in operations)
  193. {
  194. ProcessAndDispalyNumber(item, 3.14);
  195. }
  196.  
  197. string midPart = ", middle part,";
  198. Func<string, string> anonDel = delegate(string value) {
  199. string s = value + midPart;
  200. s += " last part";
  201. return s;
  202. };
  203. Console.WriteLine(anonDel("Hello"));
  204.  
  205. Func<string, string> anonDel2 = (string value) =>
  206. {
  207. string s = value + midPart;
  208. s += " last part. version 2";
  209. return s;
  210. };
  211. Console.WriteLine(anonDel2("Hello"));
  212.  
  213. Func<string, string> anonDel3 = value =>
  214. {
  215. string s = value + midPart;
  216. s += " last part. version 3";
  217. return s;
  218. };
  219. Console.WriteLine(anonDel3("Hello"));
  220.  
  221. int someValue = 5;
  222. Func<int, int> f = p1 => p1 + someValue;
  223. Console.WriteLine(f(1));
  224. someValue = 6;
  225. Console.WriteLine(f(1));
  226. //var lists = new List<string>() { "1","2"};
  227.  
  228. dynamic dyn;
  229. dyn = 100;
  230. Console.WriteLine(dyn.GetType());
  231. Console.WriteLine(dyn);
  232.  
  233. dyn = "abc中国";
  234. Console.WriteLine(dyn.GetType());
  235. Console.WriteLine(dyn);
  236. */
  237. Console.ReadKey();
  238. }
  239. }
  240. }

C#5.0 .net 4.5示例的更多相关文章

  1. .Net Core 1.0.0 RC2安装及示例教程

    前几天微软发布了.Net Core1.0.0 RC2 Preview版本,一直都想尝试下跨平台的.Net Core,一直拖到今天,也参考了下园友们的经验,闲时整理了一下安装的步骤,供大家参考. 我们要 ...

  2. RSS介绍、RSS 2.0规范说明和示例代码

    RSS是一种消息来源格式规范,用以发布经常更新资料的网站,例如博客.新闻的网摘.RSS文件,又称做摘要.网摘.更新.频道等,包含了全文或节选文字,再加上一定的属性数据.RSS让发布者自动发布信息,也使 ...

  3. OAuth 2.0 Server PHP实现示例

    需求实现三方OAuth2.0授权登录 使用OAuth服务OAuth 2.0 Server PHP 环境nginx mysqlphp 框架Yii 一 安装 项目目录下安装应用 composer.phar ...

  4. kafka producer 0.8.2.1 示例

    package test_kafka; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; i ...

  5. kafka consumer 0.8.2.1示例代码

    package test_kafka; import java.util.ArrayList; import java.util.HashMap; import java.util.List; imp ...

  6. SkylineGlobe 7.0版本 矢量数据查询示例代码

    在Pro7.0.0和7.0.1环境下测试可用. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

  7. 微信OAuth2.0网页授权php示例

    1.配置授权回调页面域名,如 www.aaa.com 2.模拟公众号的第三方网页,fn_system.php <?php if(empty($_SESSION['user'])){ header ...

  8. 部署Bookinfo示例程序详细过程和步骤(基于Kubernetes集群+Istio v1.0)

    部署Bookinfo示例程序详细过程和步骤(基于Kubernetes集群+Istio v1.0) 部署Bookinfo示例程序   在下载的Istio安装包的samples目录中包含了示例应用程序. ...

  9. C#7.0中有哪些新特性?

    以下将是 C# 7.0 中所有计划的语言特性的描述.随着 Visual Studio “15” Preview 4 版本的发布,这些特性中的大部分将活跃起来.现在是时候来展示这些特性,你也告诉借此告诉 ...

随机推荐

  1. 10分钟API Hook MessageBox

    10分钟API Hook MessageBox 分类: C++2012-04-12 22:52 877人阅读 评论(4) 收藏 举报 hookwinapidllthreadpython编程 转载注明出 ...

  2. POJ 3686 & 拆点&KM

    题意: 有n个订单,m个工厂,第i个订单在第j个工厂生产的时间为t[i][j],一个工厂可以生产多个订单,但一次只能生产一个订单,也就是说如果先生产a订单,那么b订单要等到a生产完以后再生产,问n个订 ...

  3. String, StringBuffer, StringBuilder(转载)

    http://blog.csdn.net/rmn190/article/details/1492013 String 字符串常量StringBuffer 字符串变量(线程安全)StringBuilde ...

  4. ARC指南2 - ARC的开启和禁止

    要想将非ARC的代码转换为ARC的代码,大概有2种方式: 1.使用Xcode的自动转换工具 2.手动设置某些文件支持ARC 一.Xcode的自动转换工具 Xcode带了一个自动转换工具,可以将旧的源代 ...

  5. redis 配置 linux

    附件 启动停止脚本 redis_6433: #/bin/sh #Configurations injected by install_server below.... EXEC=/usr/local/ ...

  6. JavaScript操作DOM对象

    js的精华即是操作DOM对象 [1]先看代码 <!DOCTYPE html> <html> <head> <meta charset="UTF-8& ...

  7. PAT天梯赛练习题 L2-013 红色警报(并查集+逆序加边)

    L2-013. 红色警报 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 战争中保持各个城市间的连通性非常重要.本题要求你编写一 ...

  8. 《Java核心技术卷二》笔记(二)文件操作和内存映射文件

    文件操作 上一篇已经总结了流操作,其中也包括文件的读写.文件系统除了读写以为还有很多其他的操作,如复制.移动.删除.目录浏览.属性读写等.在Java7之前,一直使用File类用于文件的操作.Java7 ...

  9. Apache Spark源码走读之14 -- Graphx实现剖析

    欢迎转载,转载请注明出处,徽沪一郎. 概要 图的并行化处理一直是一个非常热门的话题,这里头的重点有两个,一是如何将图的算法并行化,二是找到一个合适的并行化处理框架.Spark作为一个非常优秀的并行处理 ...

  10. Apache Spark源码走读之8 -- Spark on Yarn

    欢迎转载,转载请注明出处,徽沪一郎. 概要 Hadoop2中的Yarn是一个分布式计算资源的管理平台,由于其有极好的模型抽象,非常有可能成为分布式计算资源管理的事实标准.其主要职责将是分布式计算集群的 ...