How to provide timeout to a method call
Posted on 2006-11-27
I have an 3rd party API written in unmanaged C++ which is basically a proxy - it connects to an app server on the internet, receives data and raises events. My application (written in C#) uses this functionality through wrapper class written in managed C++.
Due to bugs in this API, I need to be able to detect if the call is stuck. Ideally, I would have something like this embedded in my wrapper class:
res = TimedAPIMethod(parameters, timeout);
catch (MyTimeoutException *ex)
// timeout happened, do whatever is needed
where TimedAPIMethod calls API method and provides results or throws a custom exception
if it times out.
I looked into delegates and BeginInvoke/EndInvoke but it seems not to work for me as EndInvoke must be called and I'll get stuck again waiting for delegate to finish.
I had another app where this was handled through separate worker thread launch, for each API call, which would be terminated if not finished in specified time. This doesn't look satisfactory to me beacuse it is not cheap - depending on traffic on app server, various threads in client app might launch multiple calls to API methods per second.
I'd like to hear from anyone who faced similar problems - what did you try, what did you settle for, what are the performance issues if I did this or that.