码迷,mamicode.com
首页 > 编程语言 > 详细

异步和多线程的区别

时间:2014-11-02 10:36:48      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   使用   sp   div   

多线程会有一个工作线程,占用更多的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);
            }
        }
    }
}

 

异步和多线程的区别

标签:style   blog   http   io   color   ar   使用   sp   div   

原文地址:http://www.cnblogs.com/goodspeed/p/4068380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!