.NET HTTP異步請求(適用於併發請求同時大於上千上萬個)

方法 一:async

WebRequest Request= WebRequest.Create(strURL);
Request.BeginGetResponse(new AsyncCallback(OnResponse), Request);url

protected void OnResponse(IAsyncResult ar)
{
   WebRequest wrq = (WebRequest)ar.AsyncState;
   WebResponse wrs = wrq.EndGetResponse(ar);

   // read the response ...
}string

方法二:it

class Program
    {
        private const string url = "http://";
        static async Task Main(string[] args)
        {
            await  AsyncTestTask();
        }

      

        public static async Task AsyncTestTask()
        {
            Console.WriteLine("當前任務Id是:"+Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(nameof(AsyncTestTask));
            using (var client = new WebClient())
            {
                string content = await client.DownloadStringTaskAsync(url);
                Console.WriteLine("當前任務Id是:"+Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine(content.Substring(0,100));
                Console.ReadLine();
            }

        }
    }
相關文章
相關標籤/搜索