其他分享
首页 > 其他分享> > 异步方法下载指定网址

异步方法下载指定网址

作者:互联网

异步方法下载指定网址,如果下载失败则稍等500ms在重试,如果三次都失败就停止下载,抛出下载失败

 

代码:
using System.Timers;
class Program
{
    public static System.Timers.Timer timer = new System.Timers.Timer();
    public static CancellationTokenSource cts = new CancellationTokenSource();
    public static int num = 0;
 
     static void Main(string[] args)
    {
     
        timer.Enabled = true;//设置是否执行Elapsed事件
        timer.Elapsed += new ElapsedEventHandler(Download);//绑定Elapsed事件
        timer.Interval = 500;//设置时间间隔
        Console.ReadKey();
    }
    public  static void printa(object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("请求被取消");
    }
    private  static async void Download(object source, System.Timers.ElapsedEventArgs e)
    {
        if(source!=null)
        {
            string url = source.ToString();
            cts.CancelAfter(500);
            CancellationToken cToken = cts.Token;
            await DownloadAsync("https://www.so.com/?src=lm&ls=sm2342829", cToken);
        }
        else
        {
            throw new Exception("链接为空,姐妹");
        }
    }
    public static async Task DownloadAsync(string url,CancellationToken cancelToken)
    {
        using (HttpClient client = new HttpClient())
        {
         
                string html = await client.GetStringAsync(url);
                Console.WriteLine($"{DateTime.Now}:{html}");
                num++;
            if (num == 3)
            {
                     timer.Stop();
                Console.WriteLine("下载失败");
                return;
            }
            if (cancelToken.IsCancellationRequested)
                {
                    Console.WriteLine("请求被取消");
                    return;
                }
              
 
        }
    }
}

 

标签:异步,Console,System,timer,网址,static,new,public,下载
来源: https://www.cnblogs.com/NangFah/p/16627703.html