.net 4.5 新特性 async await 通常處理程序實例

  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("\n 主方法畫圈圈結束<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   
View Code
相關文章
相關標籤/搜索