C# Async/await 异步多线程编程

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("开始获取搜狐首页字符数量");
            Task<int> task1 = CountCharsAsync("http://www.sohu.com");
            Console.WriteLine("开始获取百度首页字符数量");
            Task<int> task2 = CountCharsAsync("http://www.baidu.com");

            Console.WriteLine("Main方法中做其他事情");

            Console.WriteLine("搜狐:" + task1.Result);
            Console.WriteLine("百度:" + task2.Result);

            Console.WriteLine("====所有执行完====");
            Console.ReadLine();
        }

        static async Task<int> CountCharsAsync(string url)
        {
            WebClient wc = new WebClient();
            string result = await wc.DownloadStringTaskAsync(new Uri(url));
            /*
             * 1、以前我们用Thread.Sleep(1000),这是它的替代方式             
             * 2、Thread.Sleep 是同步延迟。 Task.Delay异步延迟。
             * 3、Thread.Sleep 会阻塞线程,Task.Delay不会。
             * 4、Thread.Sleep不能取消,Task.Delay可以。
             */
            await Task.Delay(1000);
            return result.Length;
        }
    }
}



转载于:https://www.cnblogs.com/smartsmile/p/6234094.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值