multithreading - C# Prevent Call Hang with Child Thread CallBack -


i have following code in specific scenario, hang indefinitely:

connection = new odbcconnection(connectionstring); connection.open(); 

unfortunately, hang outside control in specific scenario.

so able handle scenario , @ least throw exception.

i spin of child thread callback main thread when timeouts.

how - here attempt:

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;     }         {         resetevent.set();     } });  connectionthread.start();  var isok = resetevent.waitone(timeout);  if(exceptionthrown) {    throw exception("exception connection db"); }  if (!isok) {     connectionthread.abort();     const string messageformat = "timeout of {0} reached while creating odbcconnection {1}.";     throw exception(string.format(messageformat, timeout, connectionstring)); } 

update: here attempt using task:

odbcconnection connection = null; var connectiontask = task.factory.startnew(() => {     connection = new odbcconnection(connectionstring);     connection.open();     thread.sleep(3000); }); try {     connectiontask.wait(1000);       // wait 1 second. } catch (aggregateexception ex) {     console.writeline("exception in connection"); }  bool completed = connectiontask.iscompleted; if(!completed) {     console.writeline("connection timed-out"); } else {     connection.dosomething(); } 

why not setting timeout property?

odbcconnection.connectiontimeout = 15 

the docs on msdn state:

unlike .net framework data providers sql server , ole db, .net framework data provider odbc not support setting property connection string value, because not valid odbc connection keyword. specify connection time-out, set connectiontimeout property before calling open.

update

i think bug in mometdb there reading sql_attr_connection_timeout (see source on github), while should sql_attr_login_timout, from msdn:

to specify connection time-out, set connectiontimeout property before calling open. equivalent setting odbc sqlsetconnectattr sql_attr_login_timout attribute.

i think passing sql_attr_connection_timeout=15 connectionstring should work.


Comments