[英]Using a thread to timeout a ADO.NET query
I have a need to run a query on a couple different ADO.NET connection types (Sql and Oracle). 我需要在几个不同的ADO.NET连接类型(Sql和Oracle)上运行查询。 I want to have the ability to cancel the query after X seconds if it has not yet completed.
我希望能够在X秒后取消查询(如果尚未完成)。 I thought a thread might be a good way to approach this, so I could just kill the thread after X seconds, if it's still alive:
我认为线程可能是解决此问题的一种好方法,因此,如果它仍然存在,我可以在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());
However, this is not cancelling with the thread.Interrupt()
like other code I've used before. 但是,这并不能像我以前使用的其他代码一样用
thread.Interrupt()
取消。
How can I get this to work, or is there a better way to approach this issue? 我如何才能使其正常工作,或者有更好的方法来解决此问题?
Create a ASP.NET Web Api Controller that encapsulates your sql query, in your MVC Controller use a HttpWebRequest and specify a timeout to your request to the api. 创建一个封装SQL查询的ASP.NET Web Api控制器 ,在MVC控制器中使用HttpWebRequest并指定对api的请求超时。 The Web API call will return a JSON object containing the query result, you'll need to deserialize it in your controller using JavaScriptSerializer.Deserialize .
Web API调用将返回一个包含查询结果的JSON对象,您需要使用JavaScriptSerializer.Deserialize在控制器中反序列化该对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.