.Net 类库:线程责任

发布于 2024-11-10 15:50:33 字数 151 浏览 2 评论 0原文

我正在开发一个类库,其中一个类负责使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月隐月明月朦胧 2024-11-17 15:50:33

最佳实践是实现异步模式。这意味着,如果您的类具有 LoadXml 方法,您还可以实现 LoadXmlAsync 方法和某种 OnCompleted 事件。

您可以在此处阅读相关内容

The best practice is to implement an async pattern. This means that if your class has a LoadXmlmethod you also implement an LoadXmlAsync method and some kind of OnCompleted event.

You can read about it here

笑叹一世浮沉 2024-11-17 15:50:33

我认为这两个选择都不错。它还取决于您将在多少地方使用此方法来获取数据。如果它在多个地方使用,那么在检索文件的类中安排线程是非常有意义的。

我个人会选择最后一个,因为如果我需要在更多地方(也许以后)使用它,这会给我更大的灵活性。

在思考这个问题时,我想到了前缀方法 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文