我正在向基础存储库添加一些方法,以处理将处理使用异步任务的查询的其他代码。我基本上只是围绕现有的BeginExecuteNonQuery和EndExecuteNonQuery方法包装一个任务。
使用这样的方法有什么陷阱吗?在AsyncCallback中捕获SQL语句执行过程中发生的异常是否正确?
public class Repo
{
public class SqlCommandAsyncState<T>
{
public SqlCommand SqlCommand { get; set; }
public TaskCompletionSource<T> TaskCompletionSource { get; set; }
public SqlCommandAsyncState()
{
TaskCompletionSource = new TaskCompletionSource<T>();
}
}
private int? sqlCommand_EndExecuteNonQuery(SqlCommand sqlCommand, IAsyncResult result)
{
try
{
return sqlCommand.EndExecuteNonQuery(result);
}
catch (Exception ex)
{
// LogError(LogImportance.Fatal, ex);
}
finally
{
sqlCommand.Connection.Dispose();
}
return null;
}
private void sqlCommand_ExecuteNonQueryForIntCompleted(IAsyncResult result)
{
SqlCommandAsyncState<int?> state = result.AsyncState as SqlCommandAsyncState<int?>;
state.TaskCompletionSource.SetResult(sqlCommand_EndExecuteNonQuery(state.SqlCommand, result));
}
private void sqlCommand_ExecuteNonQueryForBoolCompleted(IAsyncResult result)
{
SqlCommandAsyncState<bool?> state = result.AsyncState as SqlCommandAsyncState<bool?>;
int? rowsAffected = sqlCommand_EndExecuteNonQuery(state.SqlCommand, result);
state.TaskCompletionSource.SetResult(rowsAffected.HasValue ? (bool?)(rowsAffected.Value > 0) : null);
}
public async Task<bool?> UpdateAsync(string commandText, SqlParameter[] parameters)
{
SqlCommandAsyncState<bool?> state = new SqlCommandAsyncState<bool?>();
SqlConnection sql_Connection = new SqlConnection(ConnectionString);
try
{
sql_Connection.Open();
state.SqlCommand = new SqlCommand(commandText, sql_Connection);
state.SqlCommand.CommandType = CommandType.StoredProcedure;
state.SqlCommand.Parameters.AddRange(parameters);
state.SqlCommand.BeginExecuteNonQuery(new AsyncCallback(sqlCommand_ExecuteNonQueryForBoolCompleted), state);
}
catch (Exception ex)
{
// LogError(LogImportance.Fatal, ex);
state.TaskCompletionSource.SetResult(null);
}
return await state.TaskCompletionSource.Task;
}
public async Task<int?> UpdateWithCountAsync(string commandText, SqlParameter[] parameters)
{
SqlCommandAsyncState<int?> state = new SqlCommandAsyncState<int?>();
SqlConnection sql_Connection = new SqlConnection(ConnectionString);
try
{
sql_Connection.Open();
state.SqlCommand = new SqlCommand(commandText, sql_Connection);
state.SqlCommand.CommandType = CommandType.StoredProcedure;
state.SqlCommand.Parameters.AddRange(parameters);
state.SqlCommand.BeginExecuteNonQuery(new AsyncCallback(sqlCommand_ExecuteNonQueryForIntCompleted), state);
}
catch (Exception ex)
{
// LogError(LogImportance.Fatal, ex);
state.TaskCompletionSource.SetResult(null);
}
return await state.TaskCompletionSource.Task;
}
}