0

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?

aligray
  • 2,812
  • 4
  • 26
  • 35
  • 1
    As you make your class library multithreaded, please be aware of taking locks. In a high-stress environment (server application), this can wind up taking thousands of locks very quickly. Use Task Parallel Library and/or concurrent collections appropriately to help minimize your locking, or the library will quickly crash and burn. – drharris Jun 01 '11 at 06:58

2 Answers2

5

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

adrianm
  • 14,468
  • 5
  • 55
  • 102
  • 1
    This is the best option, but keep in mind it only works for activities that would be considered short term, like loading a file in this case. Async would not be used for things like a serial port listener thread, which would be long running. In this case, the class library should not handle the thread, but require the user to wrap a `Listen()` method with their own thread. – drharris Jun 01 '11 at 06:28
2

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.

ChristiaanV
  • 5,401
  • 3
  • 32
  • 42