惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
J
Java Code Geeks
I
InfoQ
腾讯CDC
Vercel News
Vercel News
IT之家
IT之家
V
Visual Studio Blog
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
有赞技术团队
有赞技术团队
月光博客
月光博客
Martin Fowler
Martin Fowler
量子位
L
LangChain Blog
B
Blog
Last Week in AI
Last Week in AI
博客园 - 司徒正美
Microsoft Security Blog
Microsoft Security Blog
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans

博客园 - Goodspeed

几种常见的函数 Caesar cipher 遗传算法之背包问题 Transport scheme NOT recognized: [stomp] error running git Canvas 旋转的图片 canvas时钟 火箭起飞 让图标转起来 Tomcat启动脚本 Task中的异常处理 Parallel的陷阱 用Task代替TheadPool 使用ThreadPool代替Thread 正确停止线程 线程同步中使用信号量AutoResetEvent C#和.NET Framework的关系 为什么泛型不支持协变性? 可空值类型与值类型这间的转换
异步和多线程的区别
Goodspeed · 2014-11-02 · via 博客园 - Goodspeed

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