Your class does a lot. Start / stop is a common function that should be in its class.
public class StartStopTask { private readonly Action _action; public StartStopTask(Action action) { _action = action; } public void Start() { _task = new Task(_action); _task.Start(); } ... }
This class is easy unit test.
bool worked = false; var startstop = new StartStopTask(() => { worked = true }); startstop.Start(); startstop.Stop(new TimeSpan(0,0,0,10)); Assert.That(worked, Is.True);
Then your other classes use StartStopTask to do their job.
Print
public class ScheduledTask : StartStopTask { private IFoo _foo; public ScheduledTask(IFoo foo) : base(() => Run()) { _foo = foo; } private void Run(){
Or just delegate work
public class ScheduledTask { private IFoo _foo; private readonly StartStopTask _startstop; public ScheduledTask(IFoo foo) { _foo = foo; _startstop = new StartStopTask(() => Run()); } public void Start() { _startstop.Start(); } public void Stop(TimeSpan timeout) { _startstop.Stop(timeout); } private void Run(){
Even better would be to simply let Run be a public method and let the caller decide how to start it.
source share