What is a simple way to add a timer to a method
- by John
The following is in C#.
I'm trying to do something very simple (I think). I have a method that loads an XML document
XDocument doc = XDocument.Load(uri);
, but I don't want to tie up pc resources if there are issues (connectivity, document size, etc.).
So I'd like to be able to add a timeout variable that will cut the method off after a given number of seconds. I'm a newbie when it comes to asynchronous programming and find it confusing that there are so many examples written so many different ways . . . and none of them appear simple. I'd like a simple solution, if possible.
Here's my thoughts so far on possible solution paths:
1)
A method that wraps the existing load
public XDocument LoadXDocument(string uri, int timeout){ //code }
2)
A wrapper, but as an extension method
XDocument doc = XDocument.LoadWithTimeout(string uri, int timeout);
3)
A generic extension method.
Object obj = SomeStaticClass.LoadWithTimeout(??? method, int timeout);
3), on its face seems really nice, because it would mean being able to generically add timeouts to many different method calls and not specifically tied to one type of object, but I suspect that it is either i)impossible or ii) very difficult.
Please assist. Thanks.