我有一个asp.net MVC网站,它正在消耗一个休息的api来接收它的数据.我正在使用异步任务执行请求,因为每个页面上可能有很多.经过一段时间的正常运行时间,网站在尝试接收数据时一直抛出以下错误.
我读到这可能是由于web.config上的最大连接设置,但增加这似乎并没有太大的区别.
我也使用缓存来减少api的负载.任务被缓存,结果可以在以后使用.
我发现解决这个问题的唯一方法是回收应用程序池.任何帮助将不胜感激.
/* Code from page_load */ var currenciesTask = ApiClient.GetAsync<CurrencyListWrapper>("currencies"); var blogArticleTask = ApiClient.GetAsync<BlogArticleListWrapper>("blog/articles","limit=10"); var SEOPageTask = ApiClient.GetAsync<SEOPageListWrapper>("SEOpages"); await Task.WhenAll(currenciesTask,blogArticleTask,SEOPageTask); /* Code from data access later */ public class ApiClient : HttpClient { public static Task<T> GetAsync<T>(string operation,string query = null,bool cache = true) { // Check if task is in cache string cacheName = null; if (cache) { cacheName = String.Format("{0}_{1}_{2}",operation,query ?? String.Empty,App.GetLanguage()); var cachedTask = HttpRuntime.Cache[cacheName]; if (cachedTask != null) { return (Task<T>)cachedTask; } } // Get data task var task = GetAsyncData<T>(operation,query); // Add to cache if required if (task != null && cache) { App.AddToCache(cacheName,task); } return task; } public static async Task<T> GetAsyncData<T>(string operation,string query = null) { using (ApiClient client = new ApiClient()) { string url; if (query != null) { url = String.Format("{0}?{1}",query); } else { url = String.Format("{0}",operation); } var response = await client.GetAsync(url); return (await response.Content.ReadAsAsync<T>()); } } }
解决方法
这是错的,
The task is cached so the result can be used later.
你应该缓存结果,而不是任务.在第一次执行结束时,您的HttpClient关闭,当您尝试检索缓存任务时,它将无法正常工作.
public class ApiClient : HttpClient { public static async Task<T> GetAsync<T>(string operation,App.GetLanguage()); T cachedResult = (T)HttpRuntime.Cache[cacheName]; if (cachedResult!= null) { return Task.FromResult(cachedResult); } } // Get data task var result = await GetAsyncData<T>(operation,query); // Add to cache if required if (result != null && cache) { App.AddToCache(cacheName,result); } return result; } public static async Task<T> GetAsyncData<T>(string operation,operation); } var response = await client.GetAsync(url); return (await response.Content.ReadAsAsync<T>()); } } }