【发布时间】:2020-04-11 17:29:40
【问题描述】:
我试图使用CancellationToken 取消MySqlCommand。未请求取消时,查询成功执行。
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 消息=对象 引用未设置为对象的实例。来源=MySql.Data
堆栈跟踪:在 MySql.Data.MySqlClient.MySqlConnection.CancelQuery(Int32 超时)
在 MySql.Data.MySqlClient.MySqlCommand.Cancel() 在 ProjectName.Common.MySqlHelperService.c__DisplayClass1_1.b__1() 在 C:\Users\username\source\repos\ProjectName\Applications\ProjectName.Common\MySqlHelperService.cs:line 55 在 System.Threading.CancellationToken.ActionToActionObjShunt(对象 obj) 在 System.Threading.CancellationCallbackInfo.ExecutionContextCallback(对象 obj) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext、ContextCallback 回调、对象状态、布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback 回调、对象状态、布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback 回调、对象状态)在 System.Threading.CancellationCallbackInfo.ExecuteCallback() 在 System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments 参数)在 System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(布尔 throwOnFirstException)
【问题讨论】:
-
检查
cancellationToken是否已经初始化。 -
是的 CancellationToken 已初始化
-
你是如何以及在哪里初始化它的?
-
我将它传递给这个方法。我会更新代码
-
发布完整的异常文本,而不仅仅是消息的屏幕截图。单击
Copy Details并将文本粘贴到问题本身中。该文本包含显示 NRE 在哪里被抛出的堆栈跟踪以及涉及的方法。可能是在取消发生时该命令已被处理。或者可能是 Connector/Net 的 MySqlCommand 实现中还有另一个错误
标签: c# mysql .net mysqlcommand