Add .ConfigureAwait(false); to the await Task calls (#704)

Add .ConfigureAwait(false); to the await Task calls
This commit is contained in:
Stef Heyenrath
2021-12-24 14:08:43 +01:00
committed by GitHub
parent 1d1ff4a418
commit b5ae087b95
62 changed files with 373 additions and 372 deletions

View File

@@ -46,7 +46,7 @@ namespace WireMock.Authentication
try
{
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(_stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = configManager.GetConfigurationAsync().GetAwaiter().GetResult();
var config = configManager.GetConfigurationAsync().ConfigureAwait(false).GetAwaiter().GetResult();
var validationParameters = new TokenValidationParameters
{

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
@@ -17,7 +17,7 @@ namespace WireMock.Http
var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>()).ToArray();
if (httpResponseMessage.Content != null)
{
var stream = await httpResponseMessage.Content.ReadAsStreamAsync();
var stream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
IEnumerable<string> contentTypeHeader = null;
if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)))
{
@@ -38,7 +38,7 @@ namespace WireMock.Http
ContentEncoding = contentEncodingHeader?.FirstOrDefault(),
DecompressGZipAndDeflate = decompressGzipAndDeflate
};
responseMessage.BodyData = await BodyParser.Parse(bodyParserSettings);
responseMessage.BodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
foreach (var header in headers)

View File

@@ -108,9 +108,9 @@ namespace WireMock
}
/// <inheritdoc cref="IMapping.ProvideResponseAsync" />
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage)
public Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage)
{
return await Provider.ProvideResponseAsync(requestMessage, Settings);
return Provider.ProvideResponseAsync(requestMessage, Settings);
}
/// <inheritdoc cref="IMapping.GetRequestMatchResult" />

View File

@@ -63,8 +63,8 @@ namespace WireMock.Matchers
{
try
{
var jtoken = JToken.Parse(input);
match = IsMatch(jtoken);
var jToken = JToken.Parse(input);
match = IsMatch(jToken);
}
catch (JsonException)
{
@@ -89,8 +89,8 @@ namespace WireMock.Matchers
try
{
// Check if JToken or object
JToken jtoken = input is JToken token ? token : JObject.FromObject(input);
match = IsMatch(jtoken);
JToken jToken = input is JToken token ? token : JObject.FromObject(input);
match = IsMatch(jToken);
}
catch (JsonException)
{
@@ -113,9 +113,9 @@ namespace WireMock.Matchers
/// <inheritdoc cref="IMatcher.Name"/>
public string Name => "JsonPathMatcher";
private double IsMatch(JToken jtoken)
private double IsMatch(JToken jToken)
{
return MatchScores.ToScore(_patterns.Select(pattern => jtoken.SelectToken(pattern.GetPattern()) != null));
return MatchScores.ToScore(_patterns.Select(pattern => jToken.SelectToken(pattern.GetPattern()) != null));
}
}
}

View File

@@ -83,9 +83,9 @@ namespace WireMock.Matchers
/// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string input)
{
IStringMetric stringmetricType = GetStringMetricType();
IStringMetric stringMetricType = GetStringMetricType();
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_patterns.Select(p => stringmetricType.GetSimilarity(p.GetPattern(), input))));
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_patterns.Select(p => stringMetricType.GetSimilarity(p.GetPattern(), input))));
}
private IStringMetric GetStringMetricType()

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
#if !USE_ASPNETCORE
@@ -52,19 +52,22 @@ namespace WireMock.Owin
public Task Invoke(IContext ctx)
#endif
{
return InvokeInternal(ctx);
return InvokeInternalAsync(ctx);
}
private async Task InvokeInternal(IContext ctx)
private async Task InvokeInternalAsync(IContext ctx)
{
try
{
await Next?.Invoke(ctx);
if (Next != null)
{
await Next.Invoke(ctx).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response).ConfigureAwait(false);
}
}
}

View File

@@ -4,7 +4,6 @@ using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Util;
using JetBrains.Annotations;
#if !USE_ASPNETCORE
using Owin;
#else

View File

@@ -65,25 +65,25 @@ namespace WireMock.Owin.Mappers
DecompressGZipAndDeflate = !options.DisableRequestBodyDecompressing.GetValueOrDefault(false)
};
body = await BodyParser.Parse(bodyParserSettings);
body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
return new RequestMessage(urlDetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow };
}
private (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request)
private static (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request)
{
#if !USE_ASPNETCORE
var urldetails = UrlUtils.Parse(request.Uri, request.PathBase);
var urlDetails = UrlUtils.Parse(request.Uri, request.PathBase);
string clientIP = request.RemoteIpAddress;
#else
var urldetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase);
var urlDetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase);
var connection = request.HttpContext.Connection;
string clientIP = connection.RemoteIpAddress.IsIPv4MappedToIPv6
? connection.RemoteIpAddress.MapToIPv4().ToString()
: connection.RemoteIpAddress.ToString();
#endif
return (urldetails, clientIP);
return (urlDetails, clientIP);
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -103,7 +103,7 @@ namespace WireMock.Owin.Mappers
if (bytes != null)
{
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
}
}

View File

@@ -2,7 +2,6 @@ using System;
using System.Threading.Tasks;
using WireMock.Logging;
using System.Linq;
using HandlebarsDotNet.Helpers.Utils;
using WireMock.Matchers;
using WireMock.Http;
using WireMock.Owin.Mappers;
@@ -70,7 +69,7 @@ namespace WireMock.Owin
private async Task InvokeInternalAsync(IContext ctx)
{
var request = await _requestMapper.MapAsync(ctx.Request, _options);
var request = await _requestMapper.MapAsync(ctx.Request, _options).ConfigureAwait(false);
var logRequest = false;
ResponseMessage response = null;
@@ -115,22 +114,22 @@ namespace WireMock.Owin
if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
{
await Task.Delay(_options.RequestProcessingDelay.Value);
await Task.Delay(_options.RequestProcessingDelay.Value).ConfigureAwait(false);
}
var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request);
var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request).ConfigureAwait(false);
response = theResponse;
var responseBuilder = targetMapping.Provider as Response;
if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null)
{
if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMapping == true)
if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping.Settings?.ProxyAndRecordSettings?.SaveMapping == true)
{
_options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping);
}
if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true)
if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true)
{
var matcherMapper = new MatcherMapper(targetMapping.Settings);
var mappingConverter = new MappingConverter(matcherMapper);
@@ -187,10 +186,10 @@ namespace WireMock.Owin
// Empty catch
}
await _responseMapper.MapAsync(response, ctx.Response);
await _responseMapper.MapAsync(response, ctx.Response).ConfigureAwait(false);
}
await CompletedTask;
await CompletedTask.ConfigureAwait(false);
}
private async Task SendToWebhooksAsync(IMapping mapping, RequestMessage request, ResponseMessage response)

View File

@@ -41,13 +41,13 @@ namespace WireMock.Proxy
var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, url);
// Call the URL
var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead);
var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
// Create ResponseMessage
bool deserializeJson = !_settings.DisableJsonBodyParsing.GetValueOrDefault(false);
bool decompressGzipAndDeflate = !_settings.DisableRequestBodyDecompressing.GetValueOrDefault(false);
var responseMessage = await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson, decompressGzipAndDeflate);
var responseMessage = await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson, decompressGzipAndDeflate).ConfigureAwait(false);
IMapping mapping = null;
if (HttpStatusRangeParser.IsMatch(proxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) &&

View File

@@ -54,10 +54,7 @@ namespace WireMock.ResponseBuilders
return _delay;
}
private set
{
_delay = value;
}
private set => _delay = value;
}
/// <summary>
@@ -219,7 +216,7 @@ namespace WireMock.ResponseBuilders
BodyData = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = await bodyFactory(req),
BodyAsString = await bodyFactory(req).ConfigureAwait(false),
Encoding = encoding ?? Encoding.UTF8
}
});
@@ -385,7 +382,7 @@ namespace WireMock.ResponseBuilders
if (Delay != null)
{
await Task.Delay(Delay.Value);
await Task.Delay(Delay.Value).ConfigureAwait(false);
}
if (ProxyAndRecordSettings != null && _httpClientForProxy != null)
@@ -409,7 +406,7 @@ namespace WireMock.ResponseBuilders
_httpClientForProxy,
requestMessage,
requestMessage.ProxyUrl
);
).ConfigureAwait(false);
}
ResponseMessage responseMessage;
@@ -425,7 +422,7 @@ namespace WireMock.ResponseBuilders
}
else
{
responseMessage = await CallbackAsync(requestMessage);
responseMessage = await CallbackAsync(requestMessage).ConfigureAwait(false);
}
// Copy StatusCode from ResponseMessage (if defined)

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using WireMock.Settings;
@@ -15,7 +15,7 @@ namespace WireMock.ResponseProviders
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{
return (await _responseMessageFunc(requestMessage), null);
return (await _responseMessageFunc(requestMessage).ConfigureAwait(false), null);
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using WireMock.Settings;
@@ -17,7 +17,7 @@ namespace WireMock.ResponseProviders
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{
return (await _responseMessageFunc(requestMessage, _settings), null);
return (await _responseMessageFunc(requestMessage, _settings).ConfigureAwait(false), null);
}
}
}

View File

@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq;
using WireMock.Admin.Mappings;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Settings;

View File

@@ -77,8 +77,8 @@ namespace WireMock.Serialization
return new JsonPartialMatcher(matchBehaviour, valueForJsonPartialMatcher, ignoreCase, throwExceptionWhenMatcherFails);
case nameof(JsonPartialWildcardMatcher):
object valueForJsonPartialWilcardMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWilcardMatcher, ignoreCase, throwExceptionWhenMatcherFails);
object valueForJsonPartialWildcardMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWildcardMatcher, ignoreCase, throwExceptionWhenMatcherFails);
case nameof(JsonPathMatcher):
return new JsonPathMatcher(matchBehaviour, throwExceptionWhenMatcherFails, stringPatterns);

View File

@@ -261,7 +261,7 @@ namespace WireMock.Server
_httpClientForProxy,
requestMessage,
proxyUriWithRequestPathAndQuery.AbsoluteUri
);
).ConfigureAwait(false);
if (mapping != null)
{
@@ -673,13 +673,13 @@ namespace WireMock.Server
}
}
bool pathOrUrlmatchersValid = false;
bool pathOrUrlMatchersValid = false;
if (requestModel.Path != null)
{
if (requestModel.Path is string path)
{
requestBuilder = requestBuilder.WithPath(path);
pathOrUrlmatchersValid = true;
pathOrUrlMatchersValid = true;
}
else
{
@@ -687,7 +687,7 @@ namespace WireMock.Server
if (pathModel?.Matchers != null)
{
requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
pathOrUrlmatchersValid = true;
pathOrUrlMatchersValid = true;
}
}
}
@@ -696,7 +696,7 @@ namespace WireMock.Server
if (requestModel.Url is string url)
{
requestBuilder = requestBuilder.WithUrl(url);
pathOrUrlmatchersValid = true;
pathOrUrlMatchersValid = true;
}
else
{
@@ -704,12 +704,12 @@ namespace WireMock.Server
if (urlModel?.Matchers != null)
{
requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(_matcherMapper.Map).OfType<IStringMatcher>().ToArray());
pathOrUrlmatchersValid = true;
pathOrUrlMatchersValid = true;
}
}
}
if (pathOrUrlRequired && !pathOrUrlmatchersValid)
if (pathOrUrlRequired && !pathOrUrlMatchersValid)
{
_settings.Logger.Error("Path or Url matcher is missing for this mapping, this mapping will not be added.");
return null;

View File

@@ -114,7 +114,7 @@ namespace WireMock.Server
{
ProcessWireMockOrgJObjectAndUseStringMatcher(headers, (key, match) =>
{
requestBuilder = requestBuilder.WithHeader(key, match as IStringMatcher);
requestBuilder = requestBuilder.WithHeader(key, match);
});
}
@@ -122,7 +122,7 @@ namespace WireMock.Server
{
ProcessWireMockOrgJObjectAndUseStringMatcher(cookies, (key, match) =>
{
requestBuilder = requestBuilder.WithCookie(key, match as IStringMatcher);
requestBuilder = requestBuilder.WithCookie(key, match);
});
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -77,7 +77,7 @@ namespace WireMock.Server
[PublicAPI]
public bool DeleteLogEntry(Guid guid)
{
// Check a logentry exists with the same GUID, if so, remove it.
// Check a LogEntry exists with the same GUID, if so, remove it.
var existing = _options.LogEntries.ToList().FirstOrDefault(m => m.Guid == guid);
if (existing != null)
{

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
@@ -7,7 +7,7 @@ using Newtonsoft.Json.Linq;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Transformers.Handlebars
namespace WireMock.Transformers
{
internal class Transformer : ITransformer
{

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
@@ -107,15 +107,15 @@ namespace WireMock.Util
return BodyType.Bytes;
}
public static async Task<BodyData> Parse([NotNull] BodyParserSettings settings)
public static async Task<BodyData> ParseAsync([NotNull] BodyParserSettings settings)
{
Check.NotNull(settings, nameof(settings));
var bodyWithContentEncoding = await ReadBytesAsync(settings.Stream, settings.ContentEncoding, settings.DecompressGZipAndDeflate);
var bodyWithContentEncoding = await ReadBytesAsync(settings.Stream, settings.ContentEncoding, settings.DecompressGZipAndDeflate).ConfigureAwait(false);
var data = new BodyData
{
BodyAsBytes = bodyWithContentEncoding.Value,
DetectedCompression = bodyWithContentEncoding.Key,
BodyAsBytes = bodyWithContentEncoding.Bytes,
DetectedCompression = bodyWithContentEncoding.ContentType,
DetectedBodyType = BodyType.Bytes,
DetectedBodyTypeFromContentType = DetectBodyTypeFromContentType(settings.ContentType)
};
@@ -163,20 +163,20 @@ namespace WireMock.Util
return data;
}
private static async Task<KeyValuePair<string, byte[]>> ReadBytesAsync(Stream stream, string contentEncoding = null, bool decompressGZipAndDeflate = true)
private static async Task<(string ContentType, byte[] Bytes)> ReadBytesAsync(Stream stream, string contentEncoding = null, bool decompressGZipAndDeflate = true)
{
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
byte[] data = memoryStream.ToArray();
string type = contentEncoding?.ToLowerInvariant();
if (decompressGZipAndDeflate && (type == "gzip" || type == "deflate"))
{
return new KeyValuePair<string, byte[]>(type, CompressionUtils.Decompress(type, data));
return (type, CompressionUtils.Decompress(type, data));
}
return new KeyValuePair<string, byte[]>(null, data);
return (null, data);
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.IO;
using JetBrains.Annotations;
@@ -16,7 +16,7 @@ namespace WireMock.Util
// Default Watch Interval in Milliseconds
private const int DefaultWatchInterval = 100;
// This Dictionary keeps the track of when an event occured last for a particular file
// This Dictionary keeps the track of when an event occurred last for a particular file
private ConcurrentDictionary<string, DateTime> _lastFileEvent;
// Watch Interval in Milliseconds
@@ -176,13 +176,13 @@ namespace WireMock.Util
}
/// <summary>
/// This method searches the dictionary to find out when the last event occured
/// for a particular file. If that event occured within the specified timespan
/// This method searches the dictionary to find out when the last event occurred
/// for a particular file. If that event occurred within the specified timespan
/// it returns true, else false
/// </summary>
/// <param name="fileName">The filename to be checked</param>
/// <returns>True if an event has occured within the specified interval, False otherwise</returns>
private bool HasAnotherFileEventOccuredRecently(string fileName)
/// <returns>True if an event has occurred within the specified interval, False otherwise</returns>
private bool HasAnotherFileEventOccurredRecently(string fileName)
{
// Check dictionary only if user wants to filter recent events otherwise return value stays false.
if (!FilterRecentEvents)
@@ -194,7 +194,7 @@ namespace WireMock.Util
if (_lastFileEvent.ContainsKey(fileName))
{
// If dictionary contains the filename, check how much time has elapsed
// since the last event occured. If the timespan is less that the
// since the last event occurred. If the timespan is less that the
// specified interval, set return value to true
// and store current datetime in dictionary for this file
DateTime lastEventTime = _lastFileEvent[fileName];
@@ -206,7 +206,7 @@ namespace WireMock.Util
else
{
// If dictionary does not contain the filename,
// no event has occured in past for this file, so set return value to false
// no event has occurred in past for this file, so set return value to false
// and append filename along with current datetime to the dictionary
_lastFileEvent.TryAdd(fileName, DateTime.Now);
}
@@ -215,11 +215,11 @@ namespace WireMock.Util
}
#region FileSystemWatcher EventHandlers
// Base class Event Handlers. Check if an event has occured recently and call method
// Base class Event Handlers. Check if an event has occurred recently and call method
// to raise appropriate event only if no recent event is detected
private void OnChanged(object sender, FileSystemEventArgs e)
{
if (!HasAnotherFileEventOccuredRecently(e.FullPath))
if (!HasAnotherFileEventOccurredRecently(e.FullPath))
{
OnChanged(e);
}
@@ -227,7 +227,7 @@ namespace WireMock.Util
private void OnCreated(object sender, FileSystemEventArgs e)
{
if (!HasAnotherFileEventOccuredRecently(e.FullPath))
if (!HasAnotherFileEventOccurredRecently(e.FullPath))
{
OnCreated(e);
}
@@ -235,7 +235,7 @@ namespace WireMock.Util
private void OnDeleted(object sender, FileSystemEventArgs e)
{
if (!HasAnotherFileEventOccuredRecently(e.FullPath))
if (!HasAnotherFileEventOccurredRecently(e.FullPath))
{
OnDeleted(e);
}
@@ -243,7 +243,7 @@ namespace WireMock.Util
private void OnRenamed(object sender, RenamedEventArgs e)
{
if (!HasAnotherFileEventOccuredRecently(e.OldFullPath))
if (!HasAnotherFileEventOccurredRecently(e.OldFullPath))
{
OnRenamed(e);
}

View File

@@ -46,7 +46,7 @@ namespace WireMock.Net
while (true)
{
Logger.Info("Server running : {IsStarted}", Server.IsStarted);
await Task.Delay(SleepTime);
await Task.Delay(SleepTime).ConfigureAwait(false);
}
}