取消 DownloadStringTaskAsync 并重新启动它

本文关键字:重新启动 DownloadStringTaskAsync 取消 | 更新日期: 2023-09-27 18:35:21

我正在使用System.Net.WebClient.DownloadStringTaskAsync异步从网页下载字符串。

大约 4 次中有 5 次成功完成,但偶尔会挂起,我将不得不重新启动程序才能"重置"它。

因此,我正在考虑实现一个超时,在 5 秒后自动取消任务并重新启动它:

async void DoTasks()
{
    string output;
    int timeout = 5000;
    WebClient client = new WebClient() { Encoding = Encoding.UTF8 };
    Task<string> task = client.DownloadStringTaskAsync(url);
    if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
    {
        output = task.Result;
    }
    else
    {
        client.CancelAsync();
        DoTasks();
    }
}

但是,这将返回一个NullReferenceException

取消 DownloadStringTaskAsync 并重新启动它

我不是等待/异步方面的专家,我还在学习自己,但也许你应该做这样的事情?

using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Inline code to test");
            Console.WriteLine(StartTask(true));
            Console.WriteLine("Get actual website to test, write the length of the text only");
            Console.WriteLine(StartTask(false).Length);
            Console.Write("Press any key");
            Console.ReadKey();
        }
        static string StartTask(bool DoTestInsteadOfGetUrl)
        {
            var task = DoTasks(DoTestInsteadOfGetUrl);
            Task.WaitAny(task);
            return task.Result;
        }
        async static Task<string> DoTasks(bool DoTestInsteadOfGetUrl)
        {
            int timeout = 20;
            int count = 1;
            CancellationTokenSource cts;
            string output;                
            do
            {
                cts = new CancellationTokenSource(timeout);
                if (DoTestInsteadOfGetUrl)
                {
                    output = await Task<string>.Run(() => test(count, cts.Token), cts.Token);
                }
                else
                {
                    WebClient client = new WebClient() { Encoding = Encoding.UTF8 };
                    output = await Task<string>.Run(() => client.DownloadStringTaskAsync("http://www.google.com"), cts.Token);
                }
                if (cts.IsCancellationRequested)
                {
                    Console.WriteLine("try #" + count++);
                    timeout += DoTestInsteadOfGetUrl ? 100 : 50;
                }
            } while (cts.IsCancellationRequested);
            return output;
        }
        async static Task<string> test(int count, CancellationToken ct)
        {
            int sleep = 400 - (count * 5);
            await Task.Run(() => Task.Delay(sleep), ct);
            if (!ct.IsCancellationRequested)
            {
                Console.WriteLine("succeed #" + count);
            }
            return sleep.ToString();
        }
    }
}