作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一段代码,我想在其中应用 using
commands
中每个命令的语句数不胜数。什么是 C# 语法?
await using var transaction = await conn.BeginTransactionAsync(cancel);
IEnumerable<DbCommand> commands = BuildSnowflakeCommands(conn, tenantId);
var commandTasks = new List<Task>();
foreach (var command in commands)
{
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
commandTasks.Add(command.ExecuteNonQueryAsync(cancel));
}
try
{
await Task.WhenAll(commandTasks);
}
catch (SnowflakeDbException)
{
await transaction.RollbackAsync(cancel);
return;
}
await transaction.CommitAsync(cancel);
for
的提示成
foreach
(这显然是
错误的 ):
for (var i = 0; i < commands.Count; i++)
{
await using var command = commands[i];
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
commandTasks.Add(command.ExecuteNonQueryAsync(cancel));
}
foreach (var command in commands)
{
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
commandTasks.Add(command.ExecuteNonQueryAsync(cancel));
}
var transaction = await conn.BeginTransactionAsync(cancel);
var commands = BuildSnowflakeCommands(conn, tenantId);
var commandTasks = commands.Select(async command =>
{
await using (command)
{
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
await command.ExecuteNonQueryAsync(cancel);
}
});
try
{
await Task.WhenAll(commandTasks);
await transaction.CommitAsync(cancel);
}
catch (SnowflakeDbException)
{
await transaction.RollbackAsync(cancel);
}
finally
{
await transaction.DisposeAsync();
}
最佳答案
您可以使用 LINQ:
var commandTasks = commands.Select(async command =>
{
using (command)
{
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
await command.ExecuteNonQueryAsync(cancel);
}
});
await using var transaction = await conn.BeginTransactionAsync(cancel);
IEnumerable<DbCommand> commands = BuildSnowflakeCommands(conn, tenantId);
var commandTasks = commands.Select(async command =>
{
using (command)
{
command.CommandTimeout = commandTimeout;
command.Transaction = transaction;
await command.ExecuteNonQueryAsync(cancel);
}
});
try
{
await Task.WhenAll(commandTasks);
}
catch (SnowflakeDbException)
{
await transaction.RollbackAsync(cancel);
return;
}
await transaction.CommitAsync(cancel);
for
循环示例;
await
将导致每个命令串行发生,因为在启动下一个查询之前必须等待每个查询的完成。
关于c# - 等待在可枚举上使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62175372/
我是一名优秀的程序员,十分优秀!