Skip to content

Commit

Permalink
Call sync connection close instead of async
Browse files Browse the repository at this point in the history
Also add missing ConfigureAwait(false) and StringComparison.Ordinal,
because of a configuration mismatch between FxCop and the built-in
diagnostics analyzers.

Fixes #26790
  • Loading branch information
roji committed Dec 8, 2021
1 parent f8020cb commit 3a1cfca
Show file tree
Hide file tree
Showing 18 changed files with 56 additions and 45 deletions.
5 changes: 3 additions & 2 deletions src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,9 @@ private static async Task<bool> CreateItemOnceAsync(
(string ContainerId, JToken Document, IUpdateEntry Entry, CosmosClientWrapper Wrapper) parameters,
CancellationToken cancellationToken = default)
{
await using var stream = new MemoryStream();
await using var writer = new StreamWriter(stream, new UTF8Encoding(), bufferSize: 1024, leaveOpen: false);
using var stream = new MemoryStream();
var writer = new StreamWriter(stream, new UTF8Encoding(), bufferSize: 1024, leaveOpen: false);
await using var __ = writer.ConfigureAwait(false);
using var jsonWriter = new JsonTextWriter(writer);
Serializer.Serialize(jsonWriter, parameters.Document);
await jsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
Expand Down
5 changes: 4 additions & 1 deletion src/EFCore.Relational/Migrations/HistoryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,17 @@ public virtual async Task<IReadOnlyList<HistoryRow>> GetAppliedMigrationsAsync(
{
var command = Dependencies.RawSqlCommandBuilder.Build(GetAppliedMigrationsSql);

await using var reader = await command.ExecuteReaderAsync(
var reader = await command.ExecuteReaderAsync(
new RelationalCommandParameterObject(
Dependencies.Connection,
null,
null,
Dependencies.CurrentContext.Context,
Dependencies.CommandLogger, CommandSource.Migrations),
cancellationToken).ConfigureAwait(false);

await using var _ = reader.ConfigureAwait(false);

while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
rows.Add(new HistoryRow(reader.DbDataReader.GetString(0), reader.DbDataReader.GetString(1)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3253,7 +3253,8 @@ private void AddTable(TableExpressionBase tableExpressionBase, TableReferenceExp
{
Check.DebugAssert(_tables.Count == _tableReferences.Count, "All the tables should have their associated TableReferences.");
Check.DebugAssert(
string.Equals(GetAliasFromTableExpressionBase(tableExpressionBase), tableReferenceExpression.Alias),
string.Equals(
GetAliasFromTableExpressionBase(tableExpressionBase), tableReferenceExpression.Alias, StringComparison.Ordinal),
"Alias of table and table reference should be the same.");

var uniqueAlias = GenerateUniqueAlias(_usedAliases, tableReferenceExpression.Alias);
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore.Relational/Storage/RelationalConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -896,7 +896,7 @@ public virtual bool Close()
}
else
{
CloseDbConnectionAsync();
CloseDbConnection();
}

wasClosed = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,14 +283,16 @@ public override async Task ExecuteAsync(

try
{
await using var dataReader = await storeCommand.RelationalCommand.ExecuteReaderAsync(
var dataReader = await storeCommand.RelationalCommand.ExecuteReaderAsync(
new RelationalCommandParameterObject(
connection,
storeCommand.ParameterValues,
null,
Dependencies.CurrentContext.Context,
Dependencies.Logger, CommandSource.SaveChanges),
cancellationToken).ConfigureAwait(false);

await using var _ = dataReader.ConfigureAwait(false);
await ConsumeAsync(dataReader, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not DbUpdateException and not OperationCanceledException)
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ await _graphIterator.TraverseGraphAsync(
null,
null),
PaintActionAsync,
cancellationToken);
cancellationToken).ConfigureAwait(false);

rootEntry.StateManager.CompleteAttachGraph();
}
Expand Down
4 changes: 2 additions & 2 deletions src/EFCore/DbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -990,10 +990,10 @@ public virtual async ValueTask DisposeAsync()

if (DisposeSync(lease.IsActive, contextShouldBeDisposed))
{
await _serviceScope.DisposeAsyncIfAvailable();
await _serviceScope.DisposeAsyncIfAvailable().ConfigureAwait(false);
}

await lease.ContextDisposedAsync();
await lease.ContextDisposedAsync().ConfigureAwait(false);
}

private bool DisposeSync(bool leaseActive, bool contextShouldBeDisposed)
Expand Down
8 changes: 4 additions & 4 deletions src/EFCore/Extensions/EntityFrameworkQueryableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3127,11 +3127,11 @@ public static async Task LoadAsync<TSource>(
{
Check.NotNull(source, nameof(source));

await using (var enumerator = source.AsAsyncEnumerable().GetAsyncEnumerator(cancellationToken))
var enumerator = source.AsAsyncEnumerable().GetAsyncEnumerator(cancellationToken);
await using var _ = enumerator.ConfigureAwait(false);

while (await enumerator.MoveNextAsync().ConfigureAwait(false))
{
while (await enumerator.MoveNextAsync().ConfigureAwait(false))
{
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/EFCore/Infrastructure/Internal/LazyLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public virtual async Task LoadAsync(
{
try
{
await entry.LoadAsync(cancellationToken);
await entry.LoadAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore/Infrastructure/PooledDbContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public virtual TContext CreateDbContext()
public virtual async Task<TContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
var lease = new DbContextLease(_pool, standalone: true);
await lease.Context.SetLeaseAsync(lease, cancellationToken);
await lease.Context.SetLeaseAsync(lease, cancellationToken).ConfigureAwait(false);

return (TContext)lease.Context;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ public virtual void ProcessEntityTypeAdded(

foreach (var inverse in inverses)
{
unconfiguredNavigations.RemoveAll(n => string.Equals(n.GetSimpleMemberName(), inverse));
foreignKeyNavigations.RemoveAll(n => string.Equals(n.GetSimpleMemberName(), inverse));
unconfiguredNavigations.RemoveAll(n => string.Equals(n.GetSimpleMemberName(), inverse, StringComparison.Ordinal));
foreignKeyNavigations.RemoveAll(n => string.Equals(n.GetSimpleMemberName(), inverse, StringComparison.Ordinal));
}

if (unconfiguredNavigations.Count == 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private void Process(
var targetEntityType = targetEntityTypeBuilder.Metadata;
var targetClrType = targetEntityType.ClrType;
var inverseNavigationPropertyInfo = targetEntityType.GetRuntimeProperties().Values
.FirstOrDefault(p => string.Equals(p.GetSimpleMemberName(), attribute.Property))
.FirstOrDefault(p => string.Equals(p.GetSimpleMemberName(), attribute.Property, StringComparison.Ordinal))
?? targetEntityType.GetRuntimeProperties().Values
.FirstOrDefault(p => string.Equals(p.GetSimpleMemberName(), attribute.Property, StringComparison.OrdinalIgnoreCase));

Expand Down
8 changes: 6 additions & 2 deletions src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ private static async Task<TSource> SingleAsync<TSource>(
IAsyncEnumerable<TSource> asyncEnumerable,
CancellationToken cancellationToken = default)
{
await using var enumerator = asyncEnumerable.GetAsyncEnumerator(cancellationToken);
var enumerator = asyncEnumerable.GetAsyncEnumerator(cancellationToken);
await using var _ = enumerator.ConfigureAwait(false);

if (!await enumerator.MoveNextAsync().ConfigureAwait(false))
{
throw new InvalidOperationException(CoreStrings.SequenceContainsNoElements);
Expand All @@ -165,7 +167,9 @@ private static async Task<TSource> SingleOrDefaultAsync<TSource>(
IAsyncEnumerable<TSource> asyncEnumerable,
CancellationToken cancellationToken = default)
{
await using var enumerator = asyncEnumerable.GetAsyncEnumerator(cancellationToken);
var enumerator = asyncEnumerable.GetAsyncEnumerator(cancellationToken);
await using var _ = enumerator.ConfigureAwait(false);

if (!(await enumerator.MoveNextAsync().ConfigureAwait(false)))
{
// TODO: Convert return to Task<TSource?> when changing to C# 9
Expand Down
3 changes: 2 additions & 1 deletion src/EFCore/Storage/ExecutionStrategyExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,8 @@ public static Task<TResult> ExecuteInTransactionAsync<TState, TResult>(
async (c, s, ct) =>
{
Check.NotNull(beginTransaction, nameof(beginTransaction));
await using (var transaction = await beginTransaction(c, cancellationToken).ConfigureAwait(false))
var transaction = await beginTransaction(c, cancellationToken).ConfigureAwait(false);
await using (transaction)
{
s.CommitFailed = false;
s.Result = await s.Operation(s.State, ct).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,16 +190,15 @@ public override InterceptionResult<DbDataReader> ReaderExecuting(
return InterceptionResult<DbDataReader>.SuppressWithResult(new FakeDbDataReader());
}

public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
await base.ReaderExecutingAsync(command, eventData, result, cancellationToken);

return new ValueTask<InterceptionResult<DbDataReader>>(
InterceptionResult<DbDataReader>.SuppressWithResult(new FakeDbDataReader()));
return InterceptionResult<DbDataReader>.SuppressWithResult(new FakeDbDataReader());
}
}

Expand Down Expand Up @@ -322,15 +321,15 @@ public override InterceptionResult<object> ScalarExecuting(
return InterceptionResult<object>.SuppressWithResult(InterceptedResult);
}

public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(
public override async ValueTask<InterceptionResult<object>> ScalarExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<object> result,
CancellationToken cancellationToken = default)
{
base.ScalarExecutingAsync(command, eventData, result, cancellationToken);
await base.ScalarExecutingAsync(command, eventData, result, cancellationToken);

return new ValueTask<InterceptionResult<object>>(InterceptionResult<object>.SuppressWithResult(InterceptedResult));
return InterceptionResult<object>.SuppressWithResult(InterceptedResult);
}
}

Expand Down Expand Up @@ -382,15 +381,15 @@ public override InterceptionResult<int> NonQueryExecuting(
return InterceptionResult<int>.SuppressWithResult(2);
}
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(
public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
await base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
return new ValueTask<InterceptionResult<int>>(InterceptionResult<int>.SuppressWithResult(2));
return InterceptionResult<int>.SuppressWithResult(2);
}
}
Expand Down Expand Up @@ -852,15 +851,15 @@ public override DbDataReader ReaderExecuted(
return new CompositeFakeDbDataReader(result, new FakeDbDataReader());
}

public override ValueTask<DbDataReader> ReaderExecutedAsync(
public override async ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result,
CancellationToken cancellationToken = default)
{
base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
await base.ReaderExecutedAsync(command, eventData, result, cancellationToken);

return new ValueTask<DbDataReader>(new CompositeFakeDbDataReader(result, new FakeDbDataReader()));
return new CompositeFakeDbDataReader(result, new FakeDbDataReader());
}
}

Expand Down Expand Up @@ -999,15 +998,15 @@ public override object ScalarExecuted(
return InterceptedResult;
}

public override ValueTask<object> ScalarExecutedAsync(
public override async ValueTask<object> ScalarExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
object result,
CancellationToken cancellationToken = default)
{
base.ScalarExecutedAsync(command, eventData, result, cancellationToken);
await base.ScalarExecutedAsync(command, eventData, result, cancellationToken);

return new ValueTask<object>(InterceptedResult);
return InterceptedResult;
}
}

Expand Down
4 changes: 2 additions & 2 deletions test/EFCore.SqlServer.FunctionalTests/Query/QueryBugsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10213,8 +10213,8 @@ async Task QueryAsync(Guid parentId, Guid collectionId)
public virtual async Task Can_query_with_nav_collection_in_projection_with_split_query_in_parallel_sync()
{
var contextFactory = await CreateContext25225Async();
var task1 = Task.Factory.StartNew(() => Query(MyContext25225.Parent1Id, MyContext25225.Collection1Id));
var task2 = Task.Factory.StartNew(() => Query(MyContext25225.Parent2Id, MyContext25225.Collection2Id));
var task1 = Task.Run(() => Query(MyContext25225.Parent1Id, MyContext25225.Collection1Id));
var task2 = Task.Run(() => Query(MyContext25225.Parent2Id, MyContext25225.Collection2Id));
await Task.WhenAll(task1, task2);

void Query(Guid parentId, Guid collectionId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public void Compiled_model_is_thread_safe()
var tasks = new Task[Environment.ProcessorCount];
for (var i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
tasks[i] = Task.Run(() =>
{
using (var ctx = new EmptyContext())
{
Expand Down
10 changes: 5 additions & 5 deletions test/EFCore.Tests/DbSetTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -625,11 +625,11 @@ public async Task Can_use_Add_to_change_entity_state()
[ConditionalFact]
public async Task Can_use_Add_to_change_entity_state_async()
{
await ChangeStateWithMethod((c, e) => c.Categories.AddAsync(e), EntityState.Detached, EntityState.Added);
await ChangeStateWithMethod((c, e) => c.Categories.AddAsync(e), EntityState.Unchanged, EntityState.Added);
await ChangeStateWithMethod((c, e) => c.Categories.AddAsync(e), EntityState.Deleted, EntityState.Added);
await ChangeStateWithMethod((c, e) => c.Categories.AddAsync(e), EntityState.Modified, EntityState.Added);
await ChangeStateWithMethod((c, e) => c.Categories.AddAsync(e), EntityState.Added, EntityState.Added);
await ChangeStateWithMethod(async (c, e) => await c.Categories.AddAsync(e), EntityState.Detached, EntityState.Added);
await ChangeStateWithMethod(async (c, e) => await c.Categories.AddAsync(e), EntityState.Unchanged, EntityState.Added);
await ChangeStateWithMethod(async (c, e) => await c.Categories.AddAsync(e), EntityState.Deleted, EntityState.Added);
await ChangeStateWithMethod(async (c, e) => await c.Categories.AddAsync(e), EntityState.Modified, EntityState.Added);
await ChangeStateWithMethod(async (c, e) => await c.Categories.AddAsync(e), EntityState.Added, EntityState.Added);
}

[ConditionalFact]
Expand Down

0 comments on commit 3a1cfca

Please sign in to comment.