I want to create a class that represents a long running operation.
This class:
I have used BackgroundWorker
before but I don't have any direct experience with Thread
s or Task
s, 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 BackgroundWorker
s 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 BackgroundWorker
s 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."
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.