I have code running in a background thread that need to periodically check if the user wants to abort the work.
The question is how to implement this in a mostly SOLID environment.
- An
ICancel
interface that I inject into every class. - A public static member somewhere
Non-const statics seem to always create problems sooner or later. On the other hand the number of "standard" injections is steadily growing (ILogger, IProgressReporter, ...) so a simple thing like cancel might be good candidate to use static.
Are there other/better ways? Anyone got experience to share?
I'm using WPF and C# but the question is general.
Here is an example:
// this code is in some model assembly
public class BackgroundWorkFactory {
public IDoingBackgroundWork Worker {
get { return new DoingBackgroundWork(new Whatever()); }
}
internal class DoingBackgroundWork : IDoingBackgroundWork {
public DoingWork(IWhatever whatever) {
mWhatever = whatever;
}
public void WorkThatCanBeCanceled() {
while (!Canceled && somethingElse) {
mWhatever = whatever.DoSomthingElseThatMightAlsoAllowCancel();
...
}
}
}
// This code is in the GUI Assembly
public void StartWork() {
IDoingBackgroundWork work = factory.Worker;
Thread t = new Thread(work->WorkThatCanBeCanceled());
t.Start();
}
public void StopWork() {
// ??
}