tags:

views:

85

answers:

1

In my program I call a method

xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver());


The problem I am facing is: sometimes this function doesn't execute well within the time.

Sometimes compiler raises the time out issue after a long time of trial.. which inturn causes this part of application to shut. That is what I want to avoid.

So if it exceeds certain time say 10 seconds I need to recall the method. Is it possible to add some code lines adjacent to this, which can meet the requirement?

+4  A: 

You need to call the method on a new Thread, then call Join on the new thread with a timeout of 10 seconds.

For example:

public static bool RunWithTimeout(ThreadStart method, TimeSpan timeout, int maxTries) {
    while(maxTries > 0) {
        var thread = new Thread(method);
        thread.Start();
        if (thread.Join(timeout))
            return true;
        maxTries--;
    }
    return false;
}


if (!RunWithTimeout(
    delegate { xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); },
    TimeSpan.FromSeconds(10),
    5  //tries
))
    //Error! Waaah!
SLaks
I thank you very much for your valuable suggestion:)
infant programmer
If timeouts occur, this code will create multiple threads, all of which will continue working until completion. The background thread is still running if thread.Join times out.
Paul Williams
@Paul: Yes, it will. You could solve that by calling `Abort`, but aborts are evil.
SLaks
@SLaks, I tried using this code .. sorry .. but it is giving error ..!!
infant programmer
What error? What version of C#?
SLaks
@SLaks, first I got "Invalid expression error"
infant programmer
then I modified statement to "if(!RunWithTimeout(xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()), TimeSpan.FromSeconds(10), 5)) ;" now it is giving error saying "cannot convert void to System.threading.ThreadStart"how to get out of this error??
infant programmer
You're running C# 2.0. Try my edited code. (I had been usinga C# 3 lambda expression)
SLaks
no compilation error but output error is being shown up now, saying "Output-String(after transformation) is null", :(
infant programmer
Please ask another question.
SLaks
Oops .. I was wrong, My usage of if condition was bad, I feel sorry to trouble you and disturb your valuable time ..thanks for help and support.
infant programmer