非同期タスクを使用するクエリを処理する他のコードを処理するために、いくつかのメソッドをベース リポジトリに追加する作業を行っています。私は基本的に、既存のBeginExecuteNonQueryおよびEndExecuteNonQueryメソッドをTaskでラップしているだけです。
このような方法を使用する際の落とし穴はありますか? 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;
}
}