C#TaskCanceLedException和我的CPU拍摄100%(过程减慢了令人难以置信的速度)



我有此代码可以从多个网站下载数据。我需要以约50.000次运行此代码。

但是,在运行代码2分钟(约4000次)后,我得到了TaskCanceLedException,我的CPU达到100%,我的过程减慢了令人难以置信的减慢。

这是代码:

        public async Task<string[]> GetDataAsync(string address, string postalCode)
    {
        var path = $"{address} {postalCode}/"; // build proper path for request
        var textFrom1 = "";
        string textFrom3 = "";
        string textFrom2 = "";
        while (true)
        {
            try
            {
                textFrom1 = await client.GetStringAsync("http://website1.com/" + path);
                break;
            }
            catch (Exception e) //404
            {
                await Task.Delay(10000); // try every 10 seconds (so I do not bomb the server with requests).
            }
        }

        if (textFrom1.Split(':', ',')[1] == "0")
        {
            return new string[] { "null", "null", "null", "null", "null" };
        }

        while (true)
        {
            try
            {
                textFrom2 = await client.GetStringAsync("http://website2.com/" + textFrom1.Split('"', '"')[11]);
                break;
            }
            catch (Exception e)
            {
                await Task.Delay(10000);
            }
        }
        while (true)
        {
            try
            {
                textFrom3 = await client.GetStringAsync("http://website3.com/" + textFrom2.Split('"', '"')[3]);
                break;
            }
            catch (Exception e)
            {
                await Task.Delay(10000);
            }
        }
        var allData = await Task.Run(() => JsonConvert.DeserializeObject<List<RootObject>>(textFrom3));
        var item = allData.First();
        return new string[] { item.item1, item.item2, item.item3, item.item4, item.item5 };
    }

这就是我创建任务的方式:

        public string[][] GetAll(
        IEnumerable<string> adresses,
        IEnumerable<string> postalCodes)
    {
        // Start all tasks one by one without waiting for responses
        var tasks = adresses.Zip(postalCodes, (addr, code) => { return GetDataAsync(addr, code); });
        return Task.WhenAll(tasks).Result;
    }

有什么方法可以优化我的代码,因此我没有此例外,因此不放慢我的过程?

我希望有人可以帮助我,谢谢!

我认为您正在达到Windows可以立即处理的最大任务。您可以将50.000的请求分配给较小的组或编写一些代码来处理您的运行异步任务,以确保您不会一次启动太多任务。

此外,您可能达到最大端口数量。每次启动新连接时,您的应用程序都会打开一个新的动态端口。

最新更新