異步和多線程的區別

多線程會有一個工做線程,佔用更多的CPU。多線程

異步將使用DMA模式的IO操做異步

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();

            var url = "http://bj.58.com/";

            p.Asynchronous(url);
            p.MultiThread(url);
            Console.ReadKey();
        }

        void Asynchronous(string url)
        {
            var request = HttpWebRequest.Create(url);
            request.BeginGetResponse((IAsyncResult ar) => {
                var request_inner = ar.AsyncState as WebRequest;
                var response = request.EndGetResponse(ar);
                read(response, "Asynchronous");
            }, request);
        }

        void MultiThread(string url)
        {
            var t = new Thread(() =>
            {
                var request = HttpWebRequest.Create(url);
                var response = request.GetResponse();
                read(response, "MultiThread");
            });
            t.Start();
        }

        private static void read(WebResponse response, string funcname)
        {
            var stream = response.GetResponseStream();
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine("{0} {1}", funcname, reader.ReadToEnd().Length);
            }
        }
    }
}
相關文章
相關標籤/搜索