.Net 类库:线程责任
我正在开发一个类库,其中一个类负责使用 XDocument.Load(url)
从互联网检索 Xml 文件。鉴于此操作可能需要几秒钟才能完成,因此在其自己的线程上运行它是有意义的。
谁负责创建这个线程?检索文件的使用者或类?有这方面的最佳实践吗?
I am working on a class library and one of the classes is responsible for retrieving an Xml file using XDocument.Load(url)
from the internet. Seeing as this operation could take a few seconds to complete, it makes sense to run it on it's own thread.
Who's responsibility is it to create this thread? The consumer or the class that retrieves the file? Is there a best practice regarding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最佳实践是实现异步模式。这意味着,如果您的类具有
LoadXml
方法,您还可以实现LoadXmlAsync
方法和某种OnCompleted
事件。您可以在此处阅读相关内容
The best practice is to implement an async pattern. This means that if your class has a
LoadXml
method you also implement anLoadXmlAsync
method and some kind ofOnCompleted
event.You can read about it here
我认为这两个选择都不错。它还取决于您将在多少地方使用此方法来获取数据。如果它在多个地方使用,那么在检索文件的类中安排线程是非常有意义的。
我个人会选择最后一个,因为如果我需要在更多地方(也许以后)使用它,这会给我更大的灵活性。
在思考这个问题时,我想到了前缀方法 BeginDoSomeOperation 和 EndDoSomeOperation,这将为最后一个选项提供更多的积分。
I think both options are good. It also depends on how many places would you use this method to get the data. If it's used in multiple places than it would make perfectly sense to arrange the threading in the class that retrieves the file.
I would personally go for the last one, because that would give me more flexibility if I need to use it in more places (maybe later on).
When thinking about this question the prefixed methods BeginDoSomeOperation and EndDoSomeOperation came to mind which would give some more credits to the last option.