Shiny Donkey!
Shiny Donkey! Shiny Donkey! Shiny Donkey!
                  Fake Banner Ads!  Mini-Sites!  
    New Shiny Donkey Posts  more >>
JER
Rob Miller
Rob Miller
satishreddy
* BREAKING NEWS *  9 out of 10 former members of Minudo recommend masturbating in the office bathroom instead of shinydonkey.com

.NET Capturing/forcing a Timeout
[reply]   

03/17/04 03:26 PM EST
posted by JER email web

I've been looking for a good way to force timeouts in .NET for a while and have a working solution that I consider "meh" at best. Does anyone know of a better way to do this other than the code below? Basically, I instantiate a new class that contains one void, parameterless method and launch the method in a new Thread. Any parameters that I would have passed are sent through the object's constructor. Likewise, any return values are properties that can be referenced after the method's Thread is stopped.

For demonstration purposes, imagine you want to call a third party API that is known to contain infinite loops, so its entirely possible that making a call to this API will cause your program to block forever when it makes the call to he third party code. The example below demonstrates my way of doing this. The third party method is called "GetStockTips(string myName)"


//MAIN block of code
string myName = "Jerry";
ClugeClass myCluge = new ClugeClass(myName);

System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(m.GetData));
t.Start();

DateTime tStart = DateTime.Now;
//force timeout after 1 minute
while(t.ThreadState != System.Threading.ThreadState.Stopped && tStart > DateTime.Now.AddMinutes(-1)){
   System.Threading.Thread.Sleep(5000);
}

if(t.ThreadState != System.Threading.ThreadState.Stopped){
   t.Abort();
   throw new Exception("Third Party API method never returned");
}

string myResult = myCluge.Result;

//More code, yada yada....




//Define new class to handle third party API
private class ClugeClass{
   private string someonesName;
   private string result;

   public ClugeClass(string name){
      this.someonesName=name;
   }

   public void GetData(){
      result = ThirdPartyAPIMethod(someonesName);
   }

   public string Result {
      get { return result; }
   }

}


 

Name

 registered? log in!

E-mail (optional)

Website (optional)

  

To ensure security, this site requires unregistered users to enter a verification code:
 
Your code is:  
Enter Code:   

Note: Only registered ShinyDonkey.com users can post images. Only administrators can delete images.

  

New messages disabled indefinitely due to SPAM.



"And remember, a shiny new donkey for whoever brings me the head of Colonel Montoya..."
e-mail webmaster