加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#使用子线程回调阻止呼叫挂起

发布时间:2020-12-15 23:38:40 所属栏目:百科 来源:网络整理
导读:我有以下代码,在非常特定的情况下,将无限期挂起: connection = new OdbcConnection(connectionString);connection.Open(); 不幸的是,在这个非常具体的情况下,挂起是我无法控制的. 所以我希望能够处理这种情况,至少抛出异常. 我想旋转一个子线程,它会在超时
我有以下代码,在非常特定的情况下,将无限期挂起:

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状态的文档:

Unlike the .NET Framework data providers for SQL Server and OLE DB,the .NET Framework Data Provider for ODBC does not support setting this property as a connection string value,because it is not a valid ODBC connection keyword. To specify a connection time-out,set the ConnectionTimeout property before calling Open.

更新

我认为Mometdb中的错误是读取SQL_ATTR_CONNECTION_TIMEOUT(See source on GitHub),而它应该是SQL_ATTR_LOGIN_TIMOUT,from MSDN:

To specify a connection time-out,set the ConnectionTimeout property before calling Open. This is equivalent to setting the ODBC SQLSetConnectAttr SQL_ATTR_LOGIN_TIMOUT attribute.

我认为将SQL_ATTR_CONNECTION_TIMEOUT = 15传递给connectionstring应该可行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读