C#多线程---I/O线程实现异步请求

一、场景

利用I/O线程来模拟浏览器对服务器请求的异步操作。

二、例子

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Text;
 6 using System.Threading;
 7 using System.Threading.Tasks;
 8 
 9 namespace IOThread
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Console.ForegroundColor = ConsoleColor.DarkGreen;
16             PrintThreadInfo("Print info in Main");
17             Console.ResetColor();
18             Console.WriteLine();
19 
20             // 发出一个异步Web请求
21             WebRequest webrequest = WebRequest.Create("http://www.cnblogs.com/");
22             webrequest.BeginGetResponse(ProcessWebResponse, webrequest);
23             Console.WriteLine("");
24 
25             Console.Read();
26         }
27         // 回调方法
28         private static void ProcessWebResponse(IAsyncResult result)
29         {
30             Thread.Sleep(500);
31             PrintThreadInfo("ProcessWebResponse Method start");
32 
33             WebRequest webrequest = (WebRequest)result.AsyncState;
34             using (WebResponse webresponse = webrequest.EndGetResponse(result))
35             {
36                 Console.WriteLine("Content Length is : " + webresponse.ContentLength);
37             }
38         }
39         private static void PrintThreadInfo(string info)
40         {
41             Console.WriteLine(info);
42             Console.WriteLine($"ThreadId:{Thread.CurrentThread.ManagedThreadId}\nIsBackgroundThread:{Thread.CurrentThread.IsBackground}\nIsThreadPoolThread:{Thread.CurrentThread.IsThreadPoolThread}");
43             int workerThread = 0;
44             int ioThread = 0;
45             ThreadPool.GetMaxThreads(out workerThread, out ioThread);
46             Console.WriteLine($"MaxWorkerThread:{workerThread}\nMaxIoThread:{ioThread}");
47             int workerThreadAvailable = 0;
48             int ioThreadAvailable = 0;
49             ThreadPool.GetAvailableThreads(out workerThreadAvailable, out ioThreadAvailable);
50             Console.WriteLine($"AvailableWorkerThread:{workerThreadAvailable}\nAvailableIoThread:{ioThreadAvailable}");
51         }
52     }
53 }
View Code

运行结果如下:

 分析:

webrequest.BeginGetResponse(ProcessWebResponse, webrequest)的返回类型是IAsyncResult。在返回之前,会把IAsyncResult这个类型的变量中的AsyncState这个属性

用webrequest来填充,然后将IAsyncResult这个类型的变量传递给ProcessWebResponse回调,这个回调函数是运行在线程池的IO线程上的。

猜你喜欢

转载自www.cnblogs.com/3xiaolonglong/p/9645009.html