我试图取消 aMySqlCommand使用 a CancellationToken。未请求取消时,查询成功执行。
public async Task<int> ExecuteNonQueryAsync(string connectionString, string query,
CancellationToken cancellationToken)
{
int affectedRowsCount = 0;
await Task.Run(() =>
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
connection.Open();
command.Connection = connection;
cancellationToken.Register(() => command.Cancel());
command.CommandText = query;
command.CommandTimeout = 0;
affectedRowsCount = command.ExecuteNonQuery();
connection.Close();
}
}
});
return affectedRowsCount;
}
但是当请求取消时,它会产生 NullReferenceException。无法弄清楚什么是NULL。
我通过调用上述方法
deletedRowsInLastIteration = await
mySqlHelperService.ExecuteNonQueryAsync(
connectionString,
query,
cancellationToken);
如果我尝试
cancellationToken.ThrowIfCancellationRequested();
在调用该ExecuteNonQueryAsync()方法之前,它可以工作。但是 MySqlCommand 的取消不起作用。
这是堆栈跟踪
System.NullReferenceException HResult=0x80004003 Message=对象引用未设置为对象的实例。Source=MySql.Data
StackTrace:在 MySql.Data.MySqlClient.MySqlConnection.CancelQuery(Int32 超时)
在 C:\Users\username\source\repos\ProjectName\Applications\ProjectName.Common\MySqlHelperService.cs 中的 ProjectName.Common.MySqlHelperService.<>c__DisplayClass1_1.b__1() 中的 MySql.Data.MySqlClient.MySqlCommand.Cancel():第 55 行在 System.Threading.CancellationToken.ActionToActionObjShunt(Object obj) 在 System.Threading.CancellationCallbackInfo.ExecutionContextCallback(Object obj) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 在 System. Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 在 System.Threading.CancellationCallbackInfo.ExecuteCallback() 在 System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments args) 在 System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
