开发者

Is it possible to come over the time out issue for a function call in C#?

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 t开发者_开发问答o recall the method. Is it possible to add some code lines adjacent to this, which can meet the requirement?


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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜