向方法添加计时器的简单方法是什么
以下是 C# 语言。
我正在尝试做一些非常简单的事情(我认为)。我有一个加载 XML 文档的方法
XDocument doc = XDocument.Load(uri);
,但我不想在出现问题(连接性、文档大小等)时占用电脑资源。
所以我希望能够添加一个超时变量,该变量将在给定的秒数后切断该方法。我是异步编程的新手,并且发现有如此多的示例以多种不同的方式编写,这让我感到困惑。 。 。而且它们都显得不简单。如果可能的话,我想要一个简单的解决方案。
到目前为止,我对可能的解决方案路径的想法是:
1) 包装现有负载的方法
public XDocument LoadXDocument(string uri, int timeout){ //code }
2) 一个包装器,但作为扩展方法
XDocument doc = XDocument.LoadWithTimeout(string uri, int timeout);
3) 通用扩展方法。
Object obj = SomeStaticClass.LoadWithTimeout(??? method, int timeout);
3),从表面上看似乎非常好,因为这意味着能够一般地为许多不同的方法调用添加超时,而不是专门绑定到一种类型的对象,但我怀疑它要么 i)不可能,要么 ii)非常困难。
请帮忙。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Windows 还是 Web?请重新标记。
如果是 Windows,为什么不使用后台工作线程在与主线程不同的线程中执行该方法呢?并使用进度条来让用户知道它正在工作......完成后,如果需要提醒用户。
在 Web 中我会做同样的事情,只需将方法添加到一个全新的页面中,然后使用 jQuery 例如,使用
$.get
异步运行该方法,或者我缺少什么吗?
来自 mwilson 的回答我认为你想真正强制超时而不是使用方法的内部超时/错误。
我不会删除我的答案,而是让它保留下来,因为有人可以使用它。
is this Windows or Web ? Please retag.
If windows, why don't you use a Background Worker for executing that method in a different thread than the main one? and use a progress bar for example to let user know that it is working... when done, alert the user if needed.
in Web I would do the same thing, just add the method into a brand new page and then using jQuery for example, use
$.get
to run the method asynchronouslyor I'm missing something?
from
mwilson
answer I think you want to really force a timeout rather than use the internal timeout/error of the method.Rather than delete my answer I will let it be as someone could use it.
这应该给你一个很好的起点。
This should give you a nice starting point.