Question

I have to use an API to make a call to a third party, and ideally use the response it returns. The API has a built-in 30 second timeout, and does not allow you to set that programatically. I need it to time out in 12 seconds. Here's the call I'm making:

string response = theAPI.FunctionA(a, b, c, d);

I've been thinking I might need to use async calls to accomplish this and abort the thread at 12 seconds. Another stackoverflow question appears to come close to what I'm considering: Implement C# Generic Timeout

...I'm just wondering if this is the best way. Specifically, I keep seeing articles that warn you to call EndInvoke no matter what, and I'm wondering if Abort as in the referenced example will still close the thread appropriately? I see there were some comments with much concern about using Abort.

Was it helpful?

Solution

Aborting threads is generally a bad idea. Why not just let the call complete (or time out after 30 seconds) but ignore the result (and move on) if it takes more than 12 seconds?

OTHER TIPS

Thread.Abort will close the thread, of course, as it will call Win32 TerminateThread.

Outcome of this action will depend on how your API likes to be closed by TerminateThread.

If your method is called somthing like NuclearPlant.MoveRod() or Defibrillator.Shock(), I'd rather wait these 30 seconds.

This method gives no chance to the victim to do some cleanup:

TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.

As stated in MSDN:

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released.
  • If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top