1
0

Optimizing async tasks (ConfigureAwait(false))

This commit is contained in:
2023-11-03 10:12:30 +01:00
parent 18b9627ea4
commit ca76966827
11 changed files with 61 additions and 43 deletions

View File

@@ -40,7 +40,7 @@ namespace Microsoft.AspNetCore.Authorization
var logger = context.HttpContext.RequestServices.GetService<ILogger<BasicAuthenticationAttribute>>();
try
{
var validatorResult = await TrySetHttpUser(context);
var validatorResult = await TrySetHttpUser(context).ConfigureAwait(false);
bool isAllowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
if (isAllowAnonymous)
return;
@@ -111,7 +111,7 @@ namespace Microsoft.AspNetCore.Authorization
if (validator == null)
return null;
var result = await validator.ValidateAsync(username, password, context.HttpContext.GetRemoteIpAddress(), context.HttpContext.RequestAborted);
var result = await validator.ValidateAsync(username, password, context.HttpContext.GetRemoteIpAddress(), context.HttpContext.RequestAborted).ConfigureAwait(false);
if (result == null)
return null;

View File

@@ -66,8 +66,8 @@ namespace Microsoft.AspNetCore.Mvc.Filters
if (string.IsNullOrWhiteSpace(privateKey))
return;
await DoValidation(context);
await base.OnActionExecutionAsync(context, next);
await DoValidation(context).ConfigureAwait(false);
await base.OnActionExecutionAsync(context, next).ConfigureAwait(false);
}
private async Task DoValidation(ActionExecutingContext context)
@@ -82,7 +82,7 @@ namespace Microsoft.AspNetCore.Mvc.Filters
return;
}
await Validate(context, token);
await Validate(context, token).ConfigureAwait(false);
}
private async Task Validate(ActionExecutingContext context, string token)
@@ -93,8 +93,8 @@ namespace Microsoft.AspNetCore.Mvc.Filters
{ "secret", privateKey },
{ "response", token }
};
var response = await httpClient.PostAsync(VerificationUrl, new FormUrlEncodedContent(param));
string json = await response.Content.ReadAsStringAsync();
var response = await httpClient.PostAsync(VerificationUrl, new FormUrlEncodedContent(param)).ConfigureAwait(false);
string json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var result = JsonConvert.DeserializeObject<Response>(json);
if (result?.Success != true)

View File

@@ -58,7 +58,7 @@ namespace AMWD.Common.AspNetCore.Security.BasicAuthentication
string password = plain[(username.Length + 1)..];
var ipAddress = Context.GetRemoteIpAddress();
principal = await validator.ValidateAsync(username, password, ipAddress, Context.RequestAborted);
principal = await validator.ValidateAsync(username, password, ipAddress, Context.RequestAborted).ConfigureAwait(false);
}
catch (Exception ex)
{

View File

@@ -51,14 +51,14 @@ namespace AMWD.Common.AspNetCore.Security.BasicAuthentication
string username = plain.Split(':').First();
string password = plain[(username.Length + 1)..];
var principal = await validator.ValidateAsync(username, password, httpContext.GetRemoteIpAddress(), httpContext.RequestAborted);
var principal = await validator.ValidateAsync(username, password, httpContext.GetRemoteIpAddress(), httpContext.RequestAborted).ConfigureAwait(false);
if (principal == null)
{
SetAuthenticateRequest(httpContext, validator.Realm);
return;
}
await next.Invoke(httpContext);
await next.Invoke(httpContext).ConfigureAwait(false);
}
catch (Exception ex)
{

View File

@@ -37,14 +37,14 @@ namespace AMWD.Common.AspNetCore.Security.PathProtection
{
if (httpContext.Request.Path.StartsWithSegments(path))
{
var result = await authorizationService.AuthorizeAsync(httpContext.User, null, policyName);
var result = await authorizationService.AuthorizeAsync(httpContext.User, null, policyName).ConfigureAwait(false);
if (!result.Succeeded)
{
await httpContext.ChallengeAsync();
await httpContext.ChallengeAsync().ConfigureAwait(false);
return;
}
}
await next.Invoke(httpContext);
await next.Invoke(httpContext).ConfigureAwait(false);
}
}
}

View File

@@ -87,8 +87,8 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers
if (!string.IsNullOrWhiteSpace(hostUrl))
client.DefaultRequestHeaders.Referrer = new Uri(hostUrl);
var response = await client.GetAsync(source);
fileBytes = await response.Content.ReadAsByteArrayAsync();
var response = await client.GetAsync(source).ConfigureAwait(false);
fileBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
catch
{
@@ -109,7 +109,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers
try
{
string path = Path.Combine(env.WebRootPath, source);
fileBytes = await File.ReadAllBytesAsync(path);
fileBytes = await File.ReadAllBytesAsync(path).ConfigureAwait(false);
}
catch
{

View File

@@ -45,21 +45,21 @@ namespace Microsoft.EntityFrameworkCore
{
opts.WaitDelay = options.WaitDelay;
opts.Logger = options.Logger;
}, cancellationToken);
}, cancellationToken).ConfigureAwait(false);
var connection = database.GetDbConnection();
try
{
await connection.OpenAsync(cancellationToken);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
if (!await connection.CreateMigrationsTable(options, cancellationToken))
if (!await connection.CreateMigrationsTable(options, cancellationToken).ConfigureAwait(false))
return false;
return await connection.Migrate(options, cancellationToken);
return await connection.Migrate(options, cancellationToken).ConfigureAwait(false);
}
finally
{
await connection.CloseAsync();
await connection.CloseAsync().ConfigureAwait(false);
}
}
@@ -87,7 +87,7 @@ namespace Microsoft.EntityFrameworkCore
{
try
{
await connection.OpenAsync(cancellationToken);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
options.Logger?.LogInformation("Database connection available");
return;
}
@@ -96,7 +96,7 @@ namespace Microsoft.EntityFrameworkCore
// keep things quiet
try
{
await Task.Delay(options.WaitDelay, cancellationToken);
await Task.Delay(options.WaitDelay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -109,7 +109,7 @@ namespace Microsoft.EntityFrameworkCore
}
finally
{
await connection.CloseAsync();
await connection.CloseAsync().ConfigureAwait(false);
}
}
}
@@ -192,7 +192,7 @@ BEGIN
END;"
};
await command.ExecuteNonQueryAsync(cancellationToken);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
return true;
}
catch (Exception ex)
@@ -235,9 +235,9 @@ END;"
DatabaseProvider.SQLServer => $"SELECT [schema_file] FROM [{options.MigrationsTableName}];",
_ => $@"SELECT ""schema_file"" FROM ""{options.MigrationsTableName}"";",
};
using (var reader = await command.ExecuteReaderAsync(cancellationToken))
using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
while (await reader.ReadAsync(cancellationToken))
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
migratedFiles.Add(reader.GetString(0));
}
@@ -246,7 +246,7 @@ END;"
{
// remove path including the separator
string fileName = migrationFile.Replace(options.Path, "")[1..];
using var transaction = await connection.BeginTransactionAsync(cancellationToken);
using var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
try
{
// max length in the database: 250 chars
@@ -263,13 +263,13 @@ END;"
string sqlScript = null;
if (options.SourceAssembly == null)
{
sqlScript = await File.ReadAllTextAsync(migrationFile, cancellationToken);
sqlScript = await File.ReadAllTextAsync(migrationFile, cancellationToken).ConfigureAwait(false);
}
else
{
using var stream = options.SourceAssembly.GetManifestResourceStream(migrationFile);
using var sr = new StreamReader(stream);
sqlScript = await sr.ReadToEndAsync();
sqlScript = await sr.ReadToEndAsync().ConfigureAwait(false);
}
if (string.IsNullOrWhiteSpace(sqlScript))
@@ -278,7 +278,7 @@ END;"
options.Logger?.LogDebug($" Migrating file '{fileName}' started");
command.Transaction = transaction;
await command.ExecuteScript(sqlScript, cancellationToken);
await command.ExecuteScript(sqlScript, cancellationToken).ConfigureAwait(false);
command.CommandText = connection.GetProviderType() switch
{
@@ -286,15 +286,15 @@ END;"
DatabaseProvider.SQLServer => $"INSERT INTO [{options.MigrationsTableName}] ([schema_file], [installed_at]) VALUES ('{trimmedFileName.Replace("'", "\\'")}', '{DateTime.UtcNow:yyyy-MM-dd HH:mm}');",
_ => $@"INSERT INTO ""{options.MigrationsTableName}"" (""schema_file"", ""installed_at"") VALUES ('{trimmedFileName.Replace("'", "\\'")}', '{DateTime.UtcNow:yyyy-MM-dd HH:mm}');",
};
await command.ExecuteNonQueryAsync(cancellationToken);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
await transaction.CommitAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
command.Transaction = null;
options.Logger?.LogDebug($" Migrating file '{fileName}' successful");
}
catch (Exception ex)
{
await transaction.RollbackAsync(cancellationToken);
await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
options.Logger?.LogError($"Migrating file '{fileName}' failed: {ex.InnerException?.Message ?? ex.Message}");
return false;
}
@@ -330,7 +330,7 @@ END;"
if (!string.IsNullOrWhiteSpace(pt))
{
command.CommandText = pt;
affectedRows += await command.ExecuteNonQueryAsync(cancellationToken);
affectedRows += await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}
return affectedRows;
@@ -338,7 +338,7 @@ END;"
else
{
command.CommandText = text;
return await command.ExecuteNonQueryAsync(cancellationToken);
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}

View File

@@ -39,8 +39,8 @@ namespace AMWD.Common.Test
if (req.Content != null)
{
callback.ContentBytes = await req.Content.ReadAsByteArrayAsync();
callback.ContentString = await req.Content.ReadAsStringAsync();
callback.ContentBytes = await req.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
callback.ContentString = await req.Content.ReadAsStringAsync().ConfigureAwait(false);
}
Callbacks.Add(callback);

View File

@@ -236,7 +236,7 @@ namespace AMWD.Common.Logging
QueueItem[] items;
try
{
items = await queue.DequeueAvailableAsync(cancellationToken: token);
items = await queue.DequeueAvailableAsync(cancellationToken: token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -302,10 +302,10 @@ namespace AMWD.Common.Logging
sb.Append(message.Replace("\n", "\n" + timestampPadding + logLevelPadding));
await fileWriter.WriteLineAsync(sb.ToString());
await fileWriter.WriteLineAsync(sb.ToString()).ConfigureAwait(false);
}
await fileWriter.FlushAsync();
await fileWriter.FlushAsync().ConfigureAwait(false);
}
}

View File

@@ -425,7 +425,7 @@ namespace System.Collections.Generic
{
if (await Task.WhenAny(tcs.Task, Task.Delay(-1, cancellationToken)) == tcs.Task)
{
await tcs.Task;
await tcs.Task.ConfigureAwait(false);
return;
}

View File

@@ -5,7 +5,25 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [test/v2.1.0](https://git.am-wd.de/AM.WD/common/compare/test/v2.0.0...test/v2.1.0) - 2023-10-13
## upcoming - 0000-00-00
###### Diffs
- [AMWD.Common](https://git.am-wd.de/AM.WD/common/compare/v2.0.0...main)
- [AMWD.Common.AspNetCore](https://git.am-wd.de/AM.WD/common/compare/asp/v2.0.0...main)
- [AMWD.Common.EntityFrameworkCore](https://git.am-wd.de/AM.WD/common/compare/efc/v2.0.0...main)
- [AMWD.Common.Test](https://git.am-wd.de/AM.WD/common/compare/test/v2.1.0...main)
### Added
- Added `ConfigureAwait(false)` to async calls where appropriate
## test/v2.1.0 - 2023-10-13
###### Diffs
- [AMWD.Common.Test](https://git.am-wd.de/AM.WD/common/compare/test/v2.0.0...test/v2.1.0)
### Added