Reasonable use of threads in C #?

As part of a large automation process, we call a third-party API that does some work that calls services on another machine. Recently, we found that every time another machine is unavailable, the API call sometimes hangs up to 40 minutes when trying to connect to a remote server.

The API that we use does not offer a way to specify a timeout, and we do not want our program to wait so long, so I thought that threads would be a good way to provide a timeout. The resulting code looks something like this:

 Thread _thread = new Thread(_caller.CallServices());

 _thread.Start();
 _thread.Join(timeout);

 if (_thread.IsAlive)
 {
      _thread.Abort();
      throw new Exception("Timed-out attempting to connect.");
 }

Basically, I want APICall () to start, but if it still goes after the timeout expires, suppose it fails, kill it and continue.

# .NET. , :

/ .net , , - gotchas ?

+5
5

Thread.Abort() - , . ( , , API .

() , ping API.

, IsBackgroundThread true, .

+5

. Thread.Abort , API.

, , .exe, , / . .exe , .

+3

... , . BeginInvoke , ( )... BeginInvoke , , ...

   public delegate [ReturnType] CallerServiceDelegate
          ([parameter list for_caller.CallService]);

   CallerServiceDelegate callSvcDel = _caller.CallService;
   DateTime cutoffDate = DateTime.Now.AddSeconds(timeoutSeconds);
   IAsyncResult aR = callSvcDel.BeginInvoke([here put parameters], 
                                             AsynchCallback, null); 
   while (!aR.IsCompleted && DateTime.Now < cutoffDate)
       Thread.Sleep(500);
   if (aR.IsCompleted)
   {
      ReturnType returnValue = callSvcDel.EndInvoke(aR);
      // whatever else you need to do to handle success
   }
   else
   {
      callSvcDel.EndInvoke(aR);
      // whatever you need to do to handle timeout
   }

: AsynchCallback , EndInvoke(), , CallService() AsynchCallback instaed...

+3

, API. , , - , , , , ( - , . - ?).

Cicil, .

0

? , Thread.Abort(). ( ..), , , , , .

The idea of ​​a separate executable file makes sense. Perhaps another option would be to use AppDomains. I am not an expert in this area (I welcome refinements / corrections), but as I understand it, you would put the API call in a separate DLL and load it into a separate AppDomain. When the API call is completed or you must interrupt it, you can unload AppDomain along with the DLL. This may have the added benefit of clearing resources that a simple Thread.Abort () will not.

0
source

All Articles