Search code examples
c#multithreadingtask-parallel-librarybackgroundworker

Threading, BackgroundWorker or Task, numerous objects processed by the same method


I have a List of T objects which will need to be processed, and to speed up the processing of this list, they will be farmed out to an asynchronous process. Each object is processed by the same method, so I have a couple questions regarding various asynchronous strategies:

  1. Is BackgroundWorker or Task (TPL) preferable?
  2. Am I correct in saying that for whichever method is chosen, the list of BackgroundWorker or Task objects need to instantiate a new class containing the method to process T? In other words, if ClassA is creating the BackgroundWorker or Task objects, then they should not all point to ClassA.ProcessObject(T t), but instead instantiate new ClassB().ProcessObject(T t) as the method which does the work?

Solution

  • You're free to use whichever tool you want to accomplish the task. They two are not interchangeable, in that they have somewhat different (although overlapping) design goals. Which you prefer is something that we can't answer.

    Whether you want all of the workers to execute a method of the same instance of an object or a different instance is entirely dependent on context. Neither is inherently wrong, so long as you understand whether or not the various threads are acting on the same instance or not, and write the code accordingly. Both, in the right circumstances, can be entirely acceptable. It all comes down to whether you want the various threads to share state or not, and whether that given state is specifically designed to be accessed from multiple threads.