Search code examples
c#.netasynchronousbackgroundworker

Writing a class in an asynchronous way or just calling it asynchronously


I want to create a class that represents a long running operation.

This class:

  1. Should be constructed with some parameters,
  2. It should run the operation by calling a method,
  3. It should report its progress and it should report the end of the operation.

I have used BackgroundWorker before but I don't have any direct experience with Threads or Tasks, and I need to use .NET 3.5 so no async-await.

One way to do it is to couple the class with a BackgroundWorker. So the user will pass a BackgroundWorker to the class and the class will raise that BackgroundWorkers events. But I'm not sure if it would be good design.

The other way is to create the class, so that it will have its own events for progress change, progress end, and so on. The BackgroundWorker will be in the so called bootstrapper, and the BackgroundWorkers events will be connected to the class' events. But this seems like an unnecessary level of abstraction.

What is the usual way of designing these kinds of classes. Is it better to write it as a sort of asynchronous class, or is it better to write it in a normal way and just call it asynchronously?

Summary: In the comments, MikeCorcoran summarized the question beautifully; I am wondering "whether to write the class so it automatically does its work asynchronously within each method, or write the class so it works synchronously but is designed to be run on a background thread."


Solution

  • The answer is, "it depends."

    If there's nothing in the code that requires it to use multiple threads or to operate asynchronously, then you should write it as a normal method (or class). That way, you can test it synchronously, or even use it synchronously in simple programs. That you elect to call it from a BackgroundWorker or a Task or some other way shouldn't matter.

    Always do things in the simplest way you can, and still meet the design goals. If what the class does isn't inherently asynchronous, then don't force it to be.