我需要在几个不同的 ADO.NET 连接类型(Sql 和 Oracle)上运行查询。如果查询尚未完成,我希望能够在 X 秒后取消查询。我认为线程可能是解决此问题的好方法,所以我可以在 X 秒后杀死线程,如果它还活着的话:
var thread = new Thread((param) =>
{
try
{
string connStr = "****";
OracleConnection conn = new OracleConnection(connStr);
try
{
conn.Open();
Debug.WriteLine("Connection Open: " + DateTime.Now.ToLongTimeString());
OracleCommand cmd = new OracleCommand(param as string, conn);
Debug.WriteLine("Command Start: " + DateTime.Now.ToLongTimeString());
OracleDataReader reader = cmd.ExecuteReader();
Debug.WriteLine("Command End: " + DateTime.Now.ToLongTimeString());
conn.Close();
Debug.WriteLine("Connection Close: " + DateTime.Now.ToLongTimeString());
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
}
}
catch (ThreadInterruptedException)
{
Debug.WriteLine("Cancel: " + DateTime.Now.ToLongTimeString());
}
});
Debug.WriteLine("Start: " + DateTime.Now.ToLongTimeString());
thread.Start("begin dbms_lock.sleep(10); end;");
DateTime start = DateTime.Now;
while (thread.IsAlive)
{
if (DateTime.Now > start.AddSeconds(5))
{
thread.Interrupt();
}
}
Debug.WriteLine("End: " + DateTime.Now.ToLongTimeString());
但是,这并不能取消thread.Interrupt()
我之前使用过的其他代码。
我怎样才能让它工作,或者有没有更好的方法来解决这个问题?