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 ma开发者_如何转开发kes 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?
The best practice is to implement an async pattern. This means that if your class has a LoadXml
method you also implement an LoadXmlAsync
method and some kind of OnCompleted
event.
You can read about it here
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.
精彩评论