Async异步作业练习

353de83830225639

namespace 异步休息
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
          await Downhttp();
        }
        static async Task Downhttp()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                Console.WriteLine("请输入你要采集的网址,不要带https://,默认https,暂不支持http");
                string sr = Console.ReadLine();
                try
                    { 
                    StringBuilder sb= new StringBuilder();
                    string html=await httpClient.GetStringAsync("https://"+sr);
                    
                    if (html!= null)
                    {
                        await File.AppendAllTextAsync(@"d:ahome3.txt", html);
                        Console.WriteLine(html);
                    }
                    else {
                        for (int i = 0; i < 3; i++)
                        {
                            Console.WriteLine("下载失败第" + i + "次");
                            await Task.Delay(500);
                        }
                        Console.WriteLine("已下载");
                    }
                    Console.WriteLine(Thread.GetDomainID());

                }
                    catch (AggregateException ex)
                    {

                        throw ex;
                    }
                catch (WebException ex)
                {

                    throw ex;
                }
                catch (SocketException ex)
                {
                    throw ex;
                }
                catch (HttpRequestException ex)
                {
                    for (int i = 1; i < 4; i++)
                    {
                        Console.WriteLine("当前站点可能输入错误,下载失败第" + i + "次");

                        try
                        {
                            await httpClient.GetStringAsync("https://" + sr);
                        }
                        catch (Exception)
                        {

                            await Task.Delay(500);
                        }
                        
                    }
                    Console.WriteLine("请返回,重新正确输入需要采集的站点");
                }

            }

        }
    }
}

 

相关推荐: 异步编程async

 相关推荐: .NET面试记录(一)1.你来讲一下消息队列 消息队列就相当于给别人的待办清单。。解耦用的.没了,细节就是什么实现都行 2.你说一下.net和.net core的区别 全功能大礼包和散件自由搭配 3.ef的作用和特点 EF是强大的ORM,具体的等…

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容