Skip to content

Commit

Permalink
Add .ConfigureAwait(false); to the await Task calls (#704)
Browse files Browse the repository at this point in the history
Add .ConfigureAwait(false); to the await Task calls
  • Loading branch information
StefH authored Dec 24, 2021
1 parent 1d1ff4a commit b5ae087
Show file tree
Hide file tree
Showing 62 changed files with 373 additions and 372 deletions.
4 changes: 4 additions & 0 deletions WireMock.Net Solution.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Flurl/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=funcs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=guidb/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Jmes/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Raml/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=randomizer/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Scriban/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Sigil/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Victoor/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhook/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>
2 changes: 1 addition & 1 deletion examples/WireMock.Net.Console.Net452.Classic/MainApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ public static void Run()
.Given(Request.Create().WithPath("/random200or505async").UsingGet())
.RespondWith(Response.Create().WithCallback(async request =>
{
await Task.Delay(1);
await Task.Delay(1).ConfigureAwait(false);
int code = new Random().Next(1, 2) == 1 ? 505 : 200;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public double IsMatch(string input)
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
{
Expand Down
6 changes: 3 additions & 3 deletions src/WireMock.Net/Http/HttpResponseMessageHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
Expand All @@ -17,7 +17,7 @@ public static async Task<ResponseMessage> CreateAsync(HttpResponseMessage httpRe
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)))
{
Expand All @@ -38,7 +38,7 @@ public static async Task<ResponseMessage> CreateAsync(HttpResponseMessage httpRe
ContentEncoding = contentEncodingHeader?.FirstOrDefault(),
DecompressGZipAndDeflate = decompressGzipAndDeflate
};
responseMessage.BodyData = await BodyParser.Parse(bodyParserSettings);
responseMessage.BodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}

foreach (var header in headers)
Expand Down
4 changes: 2 additions & 2 deletions src/WireMock.Net/Mapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ public Mapping(
}

/// <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" />
Expand Down
12 changes: 6 additions & 6 deletions src/WireMock.Net/Matchers/JSONPathMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public double IsMatch(string input)
{
try
{
var jtoken = JToken.Parse(input);
match = IsMatch(jtoken);
var jToken = JToken.Parse(input);
match = IsMatch(jToken);
}
catch (JsonException)
{
Expand All @@ -89,8 +89,8 @@ public double IsMatch(object input)
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)
{
Expand All @@ -113,9 +113,9 @@ public AnyOf<string, StringPattern>[] GetPatterns()
/// <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));
}
}
}
4 changes: 2 additions & 2 deletions src/WireMock.Net/Matchers/SimMetricsMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ public SimMetricsMatcher(MatchBehaviour matchBehaviour, [NotNull] AnyOf<string,
/// <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()
Expand Down
13 changes: 8 additions & 5 deletions src/WireMock.Net/Owin/GlobalExceptionMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
#if !USE_ASPNETCORE
Expand Down Expand Up @@ -52,19 +52,22 @@ public override Task Invoke(IContext ctx)
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);
}
}
}
Expand Down
1 change: 0 additions & 1 deletion src/WireMock.Net/Owin/IWireMockMiddlewareOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Util;
using JetBrains.Annotations;
#if !USE_ASPNETCORE
using Owin;
#else
Expand Down
10 changes: 5 additions & 5 deletions src/WireMock.Net/Owin/Mappers/OwinRequestMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,25 +65,25 @@ public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddleware
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);
}
}
}
4 changes: 2 additions & 2 deletions src/WireMock.Net/Owin/Mappers/OwinResponseMapper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
Expand Down Expand Up @@ -103,7 +103,7 @@ public async Task MapAsync(ResponseMessage responseMessage, IResponse response)

if (bytes != null)
{
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
}
}

Expand Down
15 changes: 7 additions & 8 deletions src/WireMock.Net/Owin/WireMockMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Threading.Tasks;
using WireMock.Logging;
using System.Linq;
using HandlebarsDotNet.Helpers.Utils;
using WireMock.Matchers;
using WireMock.Http;
using WireMock.Owin.Mappers;
Expand Down Expand Up @@ -70,7 +69,7 @@ public Task Invoke(IContext ctx)

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;
Expand Down Expand Up @@ -115,22 +114,22 @@ private async Task InvokeInternalAsync(IContext ctx)

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);
Expand Down Expand Up @@ -187,10 +186,10 @@ private async Task InvokeInternalAsync(IContext ctx)
// 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)
Expand Down
4 changes: 2 additions & 2 deletions src/WireMock.Net/Proxy/ProxyHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ public ProxyHelper([NotNull] IWireMockServerSettings settings)
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) &&
Expand Down
13 changes: 5 additions & 8 deletions src/WireMock.Net/ResponseBuilders/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ public TimeSpan? Delay
return _delay;
}

private set
{
_delay = value;
}
private set => _delay = value;
}

/// <summary>
Expand Down Expand Up @@ -219,7 +216,7 @@ public IResponseBuilder WithBody(Func<RequestMessage, Task<string>> bodyFactory,
BodyData = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = await bodyFactory(req),
BodyAsString = await bodyFactory(req).ConfigureAwait(false),
Encoding = encoding ?? Encoding.UTF8
}
});
Expand Down Expand Up @@ -385,7 +382,7 @@ public IResponseBuilder WithRandomDelay(int minimumMilliseconds = 0, int maximum

if (Delay != null)
{
await Task.Delay(Delay.Value);
await Task.Delay(Delay.Value).ConfigureAwait(false);
}

if (ProxyAndRecordSettings != null && _httpClientForProxy != null)
Expand All @@ -409,7 +406,7 @@ string RemoveFirstOccurrence(string source, string find)
_httpClientForProxy,
requestMessage,
requestMessage.ProxyUrl
);
).ConfigureAwait(false);
}

ResponseMessage responseMessage;
Expand All @@ -425,7 +422,7 @@ string RemoveFirstOccurrence(string source, string find)
}
else
{
responseMessage = await CallbackAsync(requestMessage);
responseMessage = await CallbackAsync(requestMessage).ConfigureAwait(false);
}

// Copy StatusCode from ResponseMessage (if defined)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using WireMock.Settings;

Expand All @@ -15,7 +15,7 @@ public DynamicAsyncResponseProvider(Func<RequestMessage, Task<ResponseMessage>>

public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{
return (await _responseMessageFunc(requestMessage), null);
return (await _responseMessageFunc(requestMessage).ConfigureAwait(false), null);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Threading.Tasks;
using WireMock.Settings;

Expand All @@ -17,7 +17,7 @@ public ProxyAsyncResponseProvider(Func<RequestMessage, IWireMockServerSettings,

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);
}
}
}
1 change: 0 additions & 1 deletion src/WireMock.Net/Serialization/MappingConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Linq;
using WireMock.Admin.Mappings;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Settings;
Expand Down
4 changes: 2 additions & 2 deletions src/WireMock.Net/Serialization/MatcherMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ public IMatcher Map([CanBeNull] MatcherModel matcher)
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);
Expand Down
Loading

0 comments on commit b5ae087

Please sign in to comment.