C# Async/Await 异步操作

异步编程的核心是使用多线程,通过让不同的线程执行不同的任务,从而实现异步编程。

Demo:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace DemoAsync
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Console.WriteLine("Task Start !");
15             //DotaskWithThread();
16             DOTaskWithAsync();
17             Console.WriteLine("Task End !");
18             Console.ReadLine();
19 
20         }
21 
22         public static async void DOTaskWithAsync()
23         { 
24             Console.WriteLine("Await Taskfunction Start");
25             await Task.Run(()=> {
26                 Dotaskfunction();
27                 }); 
28         }
29         public static void Dotaskfunction()
30             {
31             for (int i = 0; i <= 5; i++) {
32 
33                 Console.WriteLine("task {0}  has been done!",i);
34             } 
35             } 
36 
37     }
38 }
View Code

 

应用实例:

public static void InterfaceTest() //OperationResult InterfaceTest()
{
OperationResult returnResult = new OperationResult();
var request = new Request(); 
string user = "{ \"UserName\":\"admin\",\"Password\":\"admin\"}";
string url = "http://127.0.0.1:8010/api/admin/auth/login";
var r = Multek.Net.Request.Send(url, HttpMethod.POST, user);
if (r.Success)
{
dynamic obj = r.Data.ToString().ToDynamicObject();
if (obj.msg == "success")
{
var objd = obj.data as dynamic;
string accToken = objd.accessToken;
string url2 = "http://127.0.0.1:8010/api/cu_int_equipment";
Dictionary<string, string> headers = new Dictionary<string, string>();
//headers.Add("Authorization", "1e90618fc-2e3db-4f36-983a-6c7258b720e5");
headers.Add("Authorization","Bearer " + accToken);
BaseManager bm = new BaseManager();
DataTable dt = bm.FillTable("SELECT * FROM [dbo].[t_EquipMaster] "); 
var data = JsonConvert.SerializeObject(dt);

var data = new[] { new { equipment = EquipID, equipmentType = "", status = BDorPM, remark = "" }, };
var datajson = JsonConvert.SerializeObject(data);


DOTaskWithAsync(data);   //异步调用另外一个操作
returnResult = Request.Send(url2, HttpMethod.POST, data, headers, "application/json");
}
}
//return returnResult;
}

public static async void DOTaskWithAsync(object data)
{
Console.WriteLine("Await Taskfunction Start");
await Task.Run(() => {
InterfacePortal.EventDistributorAPI eda = new InterfacePortal.EventDistributorAPI();
var res = eda.FireEvent<dynamic>("Equipment", data);
});
}

 

  1  /// <summary>
  2         /// 使用GET方式发送一个HTTP请求并返回其响应
  3         /// </summary>
  4         /// <param name="url">请求路径</param>
  5         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
  6         public static OperationResult Send(string url)
  7         {
  8             return Send(url, HttpMethod.GET, new JsonParameters(), null,"");
  9         }
 10 
 11         /// <summary>
 12         /// 使用GET方式发送一个HTTP请求并返回其响应
 13         /// </summary>
 14         /// <param name="url">请求路径</param>
 15         /// <param name="parameters">参数</param>
 16         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
 17         public static OperationResult Send(string url, JsonParameters parameters)
 18         {
 19             return Send(url, HttpMethod.GET, parameters, null,"");
 20         }
 21 
 22         /// <summary>
 23         /// 使用指定的方式发送一个请求
 24         /// </summary>
 25         /// <param name="url">请求路径</param>
 26         /// <param name="method">请求方式</param>
 27         /// <param name="parameters">参数</param>
 28         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
 29         public static OperationResult Send(string url,HttpMethod method, JsonParameters parameters)
 30         {
 31             return Send(url, method, parameters, null, "");
 32         }
 33 
 34         /// <summary>
 35         /// 使用指定的方式发送一个请求
 36         /// </summary>
 37         /// <param name="url">请求路径</param>
 38         /// <param name="method">请求方式</param>
 39         /// <param name="parameters">参数</param>
 40         /// <param name="headers">请求头设置</param>
 41         /// <param name="contentType">参数内容类型</param>
 42         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
 43         public static OperationResult Send(string url, HttpMethod method, JsonParameters parameters, Dictionary<string, string> headers, ContentType contentType)
 44         {
 45             return Send(url, method, parameters, headers, GetContentType(contentType));
 46         }
 47 
 48         /// <summary>
 49         /// 使用指定的方式发送一个请求
 50         /// </summary>
 51         /// <param name="url">请求路径</param>
 52         /// <param name="method">请求方式</param>
 53         /// <param name="jsonparameter">JSON格式的参数</param>
 54         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
 55         public static OperationResult Send(string url, HttpMethod method, string jsonparameter)
 56         {
 57             return Send(url, method, jsonparameter, null, GetContentType(ContentType.JSON));
 58         }
 59 
 60         /// <summary>
 61         /// 使用指定的方式发送一个请求
 62         /// </summary>
 63         /// <param name="url">请求路径</param>
 64         /// <param name="method">请求方式</param>
 65         /// <param name="headers">请求头设置</param>
 66         /// <param name="jsonparameter">JSON格式的参数</param>
 67         /// <returns></returns>
 68         public static OperationResult Send(string url, HttpMethod method,Dictionary<string,string> headers, string jsonparameter)
 69         {
 70             return Send(url, method, jsonparameter,headers, GetContentType(ContentType.JSON));
 71         }
 72 
 73         /// <summary>
 74         /// 使用指定的方式发送一个请求
 75         /// </summary>
 76         /// <param name="url">请求路径</param>
 77         /// <param name="method">请求方式</param>
 78         /// <param name="jsonparameter">JSON格式的参数</param>
 79         /// <param name="headers">请求头设置</param>
 80         /// <param name="contentType">参数内容类型</param>
 81         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
 82         public static OperationResult Send(string url, HttpMethod method, string jsonparameter, Dictionary<string, string> headers, string contentType)
 83         {
 84             OperationResult result = new OperationResult();
 85             var httpStatus = HttpStatusCode.ServiceUnavailable;
 86             Encoding Charset = Encoding.UTF8;
 87             string responseContext = "";
 88             HttpWebResponse response = null;
 89             try
 90             {
 91                 var requesturl = method != HttpMethod.POST && jsonparameter.Length>0? url + "?json=" +jsonparameter : url;
 92                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
 93                 var request = (HttpWebRequest)WebRequest.Create(requesturl);
 94                 request.Method = method.ToString();
 95                 request.ContentType = contentType;
 96                 request.PreAuthenticate = true;
 97                 request.UseDefaultCredentials = true;
 98                 if (headers != null)
 99                 {
100                     foreach (var h in headers.Keys)
101                     {
102                         request.Headers.Add(h, headers[h]);
103                     }
104                 }
105                 if (method == HttpMethod.POST)
106                 {
107                     Byte[] body = Charset.GetBytes(jsonparameter);
108                     request.ContentLength = body.Length;
109                     using (Stream os = request.GetRequestStream())
110                     {
111                         os.Write(body, 0, body.Length);
112                     }
113                 }
114                 else request.ContentLength = 0;
115                 response = (HttpWebResponse)request.GetResponse();
116                 httpStatus = response.StatusCode;
117                 using (Stream stream = response.GetResponseStream())
118                 {
119                     StreamReader sr = new StreamReader(stream, Charset);
120                     responseContext = sr.ReadToEnd().Trim();
121                     result.Data = responseContext;
122                 }
123                 response.Close();
124             }
125             catch (WebException we)
126             {
127                 HttpWebResponse httpResp = (HttpWebResponse)we.Response;
128                 result.Errors.Add("内部错误:" + httpStatus + ",message:" + we.Message);
129             }
130             return result;
131         }
132         
133         /// <summary>
134         /// 发送一个HTTP请求并返回其响应
135         /// </summary>
136         /// <param name="url">请求路径</param>
137         /// <param name="method">请求方式</param>
138         /// <param name="parameters">参数</param>
139         /// <param name="headers">请求头设置</param>
140         /// <returns>如果请求成功,请求结果通过OperationResult.Data返回(注意检查调用目标的返回结果)。</returns>
141         public static OperationResult Send(string url, HttpMethod method, JsonParameters parameters, Dictionary<string, string> headers,string contentType)
142         {
143             OperationResult result = new OperationResult();
144             if (parameters == null)
145                 parameters = new JsonParameters();
146             var httpStatus = HttpStatusCode.ServiceUnavailable;
147             Encoding Charset = Encoding.UTF8;
148             string responseContext = "";
149             HttpWebResponse response = null;
150             try
151             {
152                 var requesturl = method != HttpMethod.POST && parameters.Count>0 ? url +"?"+ parameters.ToString() : url;
153                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
154                 var request = (HttpWebRequest)WebRequest.Create(requesturl);
155                 request.Method = method.ToString();
156                 request.ContentType = contentType;
157                 request.PreAuthenticate = true;
158                 request.UseDefaultCredentials = true;
159                 if (headers != null)
160                 {
161                     foreach (var h in headers.Keys)
162                     {
163                         request.Headers.Add(h, headers[h]);
164                     }
165                 }
166                 if (method == HttpMethod.POST && parameters.Count > 0)
167                 {
168                     Byte[] body = Charset.GetBytes(parameters.ToJsonString());
169                     request.ContentLength = body.Length;
170                     using (Stream os = request.GetRequestStream())
171                     {
172                         os.Write(body, 0, body.Length);
173                     }
174                 }
175                 else request.ContentLength = 0;
176                 response = (HttpWebResponse)request.GetResponse();
177                 httpStatus = response.StatusCode;
178                 using (Stream stream = response.GetResponseStream())
179                 {
180                     StreamReader sr = new StreamReader(stream, Charset);
181                     responseContext = sr.ReadToEnd().Trim();
182                     result.Data = responseContext;
183                 }
184                 response.Close();
185             }
186             catch (WebException we)
187             {
188                 HttpWebResponse httpResp = (HttpWebResponse)we.Response;
189                 result.Errors.Add("内部错误:" + httpStatus + ",message:" + we.Message);
190             }
191             return result;
192         }
View Code

 

posted @ 2020-10-17 09:34  德平Zeng  阅读(157)  评论(0编辑  收藏  举报