I have a call to an unmanaged code library that hangs if passed an incorrect parameter.
IWorkspaceFactory workspaceFactory = _workspaceFactory.OpenFromString(connectionString);
If connectionString has an invalid value, then OpenFromString hangs. If I break execution, I can see from the call stack that control is still with the unmanaged library. Unfortunately, this method doesn't offer a timeout. What I need to do is, within my managed code, cancel the call after a certain timeout period. I've tried a couple of approaches, including the following:
Task<IWorkspace> task = new Task<IWorkspace>(() =>
{
return _workspaceFactory.OpenFromString(connectionString);
});
if (!task.Wait(10000))
{
throw new TimeoutException();
}
IWorkspace workspace = task.Result;
In this case, task.Wait() always returns false, and task.Result() is always null
, even if a valid value for connectionString is passed.
I've also tried the following approach:
IWorkspace workspace = null;
Thread thread = new Thread(() =>
{
workspace = _workspaceFactory.OpenFromString(connectionString);
});
thread.Start();
if (!thread.Join(10000))
{
throw new TimeoutException();
}
In this case, if a valid value for connectionString is passed, execution works as expected, but if an invalid value is passed, the execution still hangs in the unmanaged code, and thread.Join() never returns.
Any suggestions on how to do this?