Found additional usages for (var web = new HttpClient()) and replaced with private static readonly HttpClient HttpClient = new HttpClient();

This commit is contained in:
RaduOrleanu
2018-08-17 15:18:08 +02:00
parent 0cd3bb38ed
commit 051b595f82
4 changed files with 42 additions and 46 deletions

View File

@@ -49,7 +49,7 @@ namespace Umbraco.Core.Services
private Dictionary<string, IContentType> _importedContentTypes;
private IPackageInstallation _packageInstallation;
private readonly IUserService _userService;
private static readonly HttpClient HttpClient = new HttpClient();
public PackagingService(
ILogger logger,
@@ -89,7 +89,6 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public string FetchPackageFile(Guid packageId, Version umbracoVersion, int userId)
{
using (var httpClient = new HttpClient())
using (var uow = _uowProvider.GetUnitOfWork())
{
//includeHidden = true because we don't care if it's hidden we want to get the file regardless
@@ -97,7 +96,7 @@ namespace Umbraco.Core.Services
byte[] bytes;
try
{
bytes = httpClient.GetByteArrayAsync(url).GetAwaiter().GetResult();
bytes = HttpClient.GetByteArrayAsync(url).GetAwaiter().GetResult();
}
catch (HttpRequestException ex)
{
@@ -1746,7 +1745,7 @@ namespace Umbraco.Core.Services
internal InstallationSummary InstallPackage(string packageFilePath, int userId = 0, bool raiseEvents = false)
{
var metaData = GetPackageMetaData(packageFilePath);
var metaData = GetPackageMetaData(packageFilePath);
if (raiseEvents)
{

View File

@@ -27,6 +27,8 @@ namespace Umbraco.Web.Editors
[WebApi.UmbracoAuthorize]
public class DashboardController : UmbracoApiController
{
//we have just one instance of HttpClient shared for the entire application
private static readonly HttpClient HttpClient = new HttpClient();
//we have baseurl as a param to make previewing easier, so we can test with a dev domain from client side
[ValidateAngularAntiForgeryToken]
public async Task<JObject> GetRemoteDashboardContent(string section, string baseUrl = "https://dashboard.umbraco.org/")
@@ -54,13 +56,10 @@ namespace Umbraco.Web.Editors
//content is null, go get it
try
{
using (var web = new HttpClient())
{
//fetch dashboard json and parse to JObject
var json = await web.GetStringAsync(url);
content = JObject.Parse(json);
result = content;
}
//fetch dashboard json and parse to JObject
var json = await HttpClient.GetStringAsync(url);
content = JObject.Parse(json);
result = content;
ApplicationContext.ApplicationCache.RuntimeCache.InsertCacheItem<JObject>(key, () => result, new TimeSpan(0, 30, 0));
}
@@ -93,17 +92,17 @@ namespace Umbraco.Web.Editors
//content is null, go get it
try
{
using (var web = new HttpClient())
{
//fetch remote css
content = await web.GetStringAsync(url);
// using (var web = new HttpClient())
// {
//fetch remote css
content = await HttpClient.GetStringAsync(url);
//can't use content directly, modified closure problem
result = content;
//can't use content directly, modified closure problem
result = content;
//save server content for 30 mins
ApplicationContext.ApplicationCache.RuntimeCache.InsertCacheItem<string>(key, () => result, new TimeSpan(0, 30, 0));
}
//save server content for 30 mins
ApplicationContext.ApplicationCache.RuntimeCache.InsertCacheItem<string>(key, () => result, new TimeSpan(0, 30, 0));
// }
}
catch (HttpRequestException ex)
{
@@ -119,12 +118,12 @@ namespace Umbraco.Web.Editors
Content = new StringContent(result, Encoding.UTF8, "text/css")
};
}
[ValidateAngularAntiForgeryToken]
public IEnumerable<Tab<DashboardControl>> GetDashboard(string section)
{
var dashboardHelper = new DashboardHelper(Services.SectionService);
return dashboardHelper.GetDashboard(section, Security.CurrentUser);
return dashboardHelper.GetDashboard(section, Security.CurrentUser);
}
}
}

View File

@@ -23,6 +23,7 @@ namespace Umbraco.Web.Install
{
internal class InstallHelper
{
private static readonly HttpClient HttpClient = new HttpClient();
private readonly UmbracoContext _umbContext;
private InstallationType? _installationType;
@@ -199,8 +200,7 @@ namespace Umbraco.Web.Install
UmbracoVersion.Current);
using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
using (var httpClient = new HttpClient())
using (var response = httpClient.SendAsync(request).Result)
using (var response = HttpClient.SendAsync(request).Result)
{
packages = response.Content.ReadAsAsync<IEnumerable<Package>>().Result.ToList();
}
@@ -213,4 +213,4 @@ namespace Umbraco.Web.Install
return packages;
}
}
}
}

View File

@@ -17,11 +17,12 @@ namespace Umbraco.Web.Scheduling
internal class ScheduledTasks : RecurringTaskBase
{
private static readonly HttpClient HttpClient = new HttpClient();
private readonly ApplicationContext _appContext;
private readonly IUmbracoSettingsSection _settings;
private static readonly Hashtable ScheduledTaskTimes = new Hashtable();
public ScheduledTasks(IBackgroundTaskRunner<RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
public ScheduledTasks(IBackgroundTaskRunner<RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
ApplicationContext appContext, IUmbracoSettingsSection settings)
: base(runner, delayMilliseconds, periodMilliseconds)
{
@@ -61,28 +62,25 @@ namespace Umbraco.Web.Scheduling
private async Task<bool> GetTaskByHttpAync(string url, CancellationToken token)
{
using (var wc = new HttpClient())
if (Uri.TryCreate(_appContext.UmbracoApplicationUrl, UriKind.Absolute, out var baseUri))
{
if (Uri.TryCreate(_appContext.UmbracoApplicationUrl, UriKind.Absolute, out var baseUri))
{
wc.BaseAddress = baseUri;
}
var request = new HttpRequestMessage(HttpMethod.Get, url);
//TODO: pass custom the authorization header, currently these aren't really secured!
//request.Headers.Authorization = AdminTokenAuthorizeAttribute.GetAuthenticationHeaderValue(_appContext);
try
{
var result = await wc.SendAsync(request, token).ConfigureAwait(false); // ConfigureAwait(false) is recommended? http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
return result.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
LogHelper.Error<ScheduledTasks>("An error occurred calling web task for url: " + url, ex);
}
return false;
HttpClient.BaseAddress = baseUri;
}
var request = new HttpRequestMessage(HttpMethod.Get, url);
//TODO: pass custom the authorization header, currently these aren't really secured!
//request.Headers.Authorization = AdminTokenAuthorizeAttribute.GetAuthenticationHeaderValue(_appContext);
try
{
var result = await HttpClient.SendAsync(request, token).ConfigureAwait(false); // ConfigureAwait(false) is recommended? http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
return result.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
LogHelper.Error<ScheduledTasks>("An error occurred calling web task for url: " + url, ex);
}
return false;
}
public override async Task<bool> PerformRunAsync(CancellationToken token)