编辑:最终为我工作的解决方案是使用异步 ADO.NET 方法。BeginExecute...
和EndExecute...
这是一段在检查 aBackgroundWorker
是否请求取消时异步执行查询的代码片段。如果查询运行完成,该函数返回 true,如果执行取消,则返回 false。
代码应该从BackgroundWorker
'sDoWork
函数中的某个地方调用。
SqlCommand command = new SqlCommand(query, connectionObj);
IAsyncResult result = command.BeginExecuteReader(); // end async execution
// check for user cancellation while result is not complete
while (!result.IsCompleted)
{
if (myBackgroundWorker.CancellationPending)
{
command.Cancel(); // cancel the existing command
try
{
command.EndExecuteReader(result); // cancel async execution
}
catch (SqlException e)
{
// will always enter here due to command.Cancel()
// this is expected
}
return false;
}
Thread.Sleep(100); // sleep so loop doesn't consume all the resources
}
// result is complete, do something with data
using (SqlDataReader reader = command.EndExecuteReader(result))
{
DataTable table = new DataTable();
table.Load(reader);
}
// do something with table
return true;