C#使用子线程回调阻止呼叫挂起
我有以下代码,在非常特定的情况下,将无限期挂起:
connection = new OdbcConnection(connectionString); connection.Open(); 不幸的是,在这个非常具体的情况下,挂起是我无法控制的. 所以我希望能够处理这种情况,至少抛出异常. 我想旋转一个子线程,它会在超时时回调主线程. 你会怎么做 – 这是我的尝试: OdbcConnection connection = null; var timeout = TimeSpan.FromSeconds(15); var resetEvent = new ManualResetEvent(false); bool exceptionThrown = false; var connectionThread = new Thread(() => { try { connection = new OdbcConnection(connectionString); connection.Open(); } catch(Exception e) { exceptionThrown = true; } finally { resetEvent.Set(); } }); connectionThread.Start(); var isOk = resetEvent.WaitOne(timeout); if(exceptionThrown) { throw now Exception("Exception connection to DB"); } if (!isOk) { connectionThread.Abort(); const string messageFormat = "Timeout of {0} reached while creating OdbcConnection to {1}."; throw now Exception(string.Format(messageFormat,timeout,connectionString)); } 更新: OdbcConnection connection = null; var connectionTask = Task.Factory.StartNew(() => { connection = new OdbcConnection(connectionString); connection.Open(); Thread.Sleep(3000); }); try { connectionTask.Wait(1000); // Wait for 1 second. } catch (AggregateException ex) { Console.WriteLine("Exception in connection"); } bool completed = connectionTask.IsCompleted; if(!completed) { Console.WriteLine("Connection Timed-out"); } else { connection.DoSomething(); } 解决方法
为什么不设置Timeout属性?
OdbcConnection.ConnectionTimeout = 15 关于MSDN状态的文档:
更新 我认为Mometdb中的错误是读取SQL_ATTR_CONNECTION_TIMEOUT(See source on GitHub),而它应该是SQL_ATTR_LOGIN_TIMOUT,from MSDN:
我认为将SQL_ATTR_CONNECTION_TIMEOUT = 15传递给connectionstring应该可行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |