1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading; 5 using System.Threading.Tasks; 6 using System.Web; 7 8 namespace PaoTui.ServerSide.WeChat 9 { 10 /// <summary> 11 /// AsyncHandler1 的摘要说明 12 /// </summary> 13 public class AsyncHandler1 : IHttpHandler 14 { 15 16 public void ProcessRequest(HttpContext context) 17 { 18 context.Response.ContentType = "text/html"; 19 if (context.Request.QueryString["para"] == "1") 20 { 21 context.Response.Write("主方法开始<br/>"); 22 //Task<int> result = GetIntResult(context); 带参数 方法 23 GetIntResult(context);//不带参数方法 24 context.Response.Write(" 主方法开始画圈圈<br/>"); 25 for (int i = 0; i < 100; i++) 26 { 27 context.Response.Write("○"); 28 } 29 context.Response.Write(" 主方法画圈圈结束<br/>"); 30 context.Response.Write("开始判断异步方法是否完成<br/>"); 31 //if (!result.IsCompleted) 32 //{ 33 // context.Response.Write("异步方法未完成,开始等待<br/>"); 34 // result.Wait(); 35 //} 36 //else 37 //{ 38 // context.Response.Write("异步方法为完成<br/>"); 39 //} 40 //context.Response.Write(" 最终结果:" + result.Result); 41 context.Response.Write("<br/>主方法结束"); 42 } 43 else 44 { 45 46 context.Response.Write(" 同步方法开始,开始计算0到2的和<br/>"); 47 48 int r = 0; 49 for (int i = 0; i < 5; i++) 50 { 51 r += i; 52 Thread.Sleep(1000); 53 } 54 context.Response.Write(" 主方法开始画圈圈<br/>"); 55 for (int i = 0; i < 100; i++) 56 { 57 context.Response.Write("○"); 58 } 59 context.Response.Write("<br/>主方法结束"); 60 } 61 62 } 63 64 public bool IsReusable 65 { 66 get 67 { 68 return false; 69 } 70 } 71 ///带参数返回方法 72 //public async Task<int> GetIntResult(HttpContext context) 73 //{ 74 75 // context.Response.Write(" 异步方法开始调用<br/>"); 76 // int result = await Task<int>.Run<int>(() => 77 // { 78 // context.Response.Write(" await异步操作开始,开始计算0到2的和<br/>"); 79 // int r = 0; 80 // for (int i = 0; i < 2; i++) 81 // { 82 // r += i; 83 // Thread.Sleep(1000); 84 // } 85 // context.Response.Write(" await异步操作结束<br/>"); 86 // return r; 87 // }); 88 // context.Response.Write(" 异步方法调用结束<br/>"); 89 // return result; 90 //} 91 /// <summary> 92 /// 不带参数返回方法 93 /// </summary> 94 /// <param name="context"></param> 95 public async void GetIntResult(HttpContext context) 96 { 97 98 context.Response.Write(" 异步方法开始调用<br/>"); 99 await Task.Run(() => 100 { 101 context.Response.Write(" await异步操作开始,开始计算0到2的和<br/>"); 102 int r = 0; 103 for (int i = 0; i < 5; i++) 104 { 105 r += i; 106 Thread.Sleep(1000); 107 } 108 context.Response.Write(" await异步操作结束<br/>" + r); 109 110 }); 111 //context.Response.Write(" 异步方法调用结束<br/>" + r); 112 113 } 114 } 115 } 116