为什么.net核心API取消请求? [英] Why is my .net core API cancelling requests?

查看:81
本文介绍了为什么.net核心API取消请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环的aync方法:

I have a an aync method that is looped:

    private Task<HttpResponseMessage> GetResponseMessage(Region region, DateTime startDate, DateTime endDate)
    {
        var longLatString = $"q={region.LongLat.Lat},{region.LongLat.Long}";
        var startDateString = $"{startDateQueryParam}={ConvertDateTimeToApixuQueryString(startDate)}";
        var endDateString = $"{endDateQueryParam}={ConvertDateTimeToApixuQueryString(endDate)}";
        var url = $"http://api?key={Config.Key}&{longLatString}&{startDateString}&{endDateString}";
        return Client.GetAsync(url);
    }

然后我将响应保存到我的ef核心数据库中,但是在在某些情况下,我会收到此异常消息:操作被取消

I then take the response and save it to my ef core database, however in some instances I get this Exception message: The Operaiton was canceled

我真的不明白。这是TCP握手问题吗?

I really dont understand that. This is a TCP handshake issue?

编辑:

对于上下文,我正在进行许多此类调用,对写入db的方法的响应(这也是如此之慢,令人难以置信):

For context I am making many of these calls, passing response to the method that writes to db (which is also so slow Its unbelievable):

private async Task<int> WriteResult(Response apiResponse, Region region)
        {
            // since context is not thread safe we ensure we have a new one for each insert
            // since a .net core app can insert data at the same time from different users different instances of context
            // must be thread safe
            using (var context = new DalContext(ContextOptions))
            {
                var batch = new List<HistoricalWeather>();
                foreach (var forecast in apiResponse.Forecast.Forecastday)
                {
                    // avoid inserting duplicates
                    var existingRecord = context.HistoricalWeather
                        .FirstOrDefault(x => x.RegionId == region.Id &&
                            IsOnSameDate(x.Date.UtcDateTime, forecast.Date));
                    if (existingRecord != null)
                    {
                        continue;
                    }

                    var newHistoricalWeather = new HistoricalWeather
                    {
                        RegionId = region.Id,
                        CelsiusMin = forecast.Day.Mintemp_c,
                        CelsiusMax = forecast.Day.Maxtemp_c,
                        CelsiusAverage = forecast.Day.Avgtemp_c,
                        MaxWindMph = forecast.Day.Maxwind_mph,
                        PrecipitationMillimeters = forecast.Day.Totalprecip_mm,
                        AverageHumidity = forecast.Day.Avghumidity,
                        AverageVisibilityMph = forecast.Day.Avgvis_miles,
                        UvIndex = forecast.Day.Uv,
                        Date = new DateTimeOffset(forecast.Date),
                        Condition = forecast.Day.Condition.Text
                    };

                    batch.Add(newHistoricalWeather);
                }

                context.HistoricalWeather.AddRange(batch);
                var inserts = await context.SaveChangesAsync();

                return inserts;
            }

编辑:我正在拨打150,000个电话。我知道这是有问题的,因为所有内存都存储在内存中,甚至在保存之前就已经存在了,但这就是我试图使运行速度更快的地方。。。只有我猜我的实际编写代码正在阻塞:/

I am making 150,000 calls. I know this is questionable since It all goes in memory I guess before even doing a save but this is where I got to in trying to make this run faster... only I guess my actual writing code is blocking :/

var dbInserts = await Task.WhenAll(
                getTasks // the list of all api get requests
                .Select(async x => {
                    // parsed can be null if get failed
                    var parsed = await ParseApixuResponse(x.Item1); // readcontentasync and just return the deserialized json
                    return new Tuple<ApiResult, Region>(parsed, x.Item2);
                })
                .Select(async x => {
                    var finishedGet = await x;
                    if(finishedGet.Item1 == null)
                    {
                        return 0;
                    }

                    return await writeResult(finishedGet.Item1, finishedGet.Item2);
                })
            );


推荐答案

.net核心具有注释中回答的是DefaultConnectionLimit 设置。

.net core has a DefaultConnectionLimit setting as answered in comments.

这限制了到特定域的传出连接,以确保不占用所有端口等。

this limits outgoing connections to specific domains to ensure all ports are not taken etc.

我的并行工作不正确,导致它超出了限制-我所读的内容在.net内核上不应为2,而是-并且导致连接关闭,然后接收响应。

i did my parallel work incorrectly causing it to go over the limit - which everything i read says should not be 2 on .net core but it was - and that caused connections to close before receiving responses.

我把它做的更大,并行工作正确,然后又降低了。

I made it greater, did parallel work correctly, lowered it again.

这篇关于为什么.net核心API取消请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆