internal class Program
{
static void Main(string[] args)
{
var printService = new PrintService();
var testService = new TestService(printService);
testService.StartExecuting();
Thread.Sleep(5000);
testService.StopExecuting();
Console.WriteLine("Done");
}
}
class PrintService
{
public void PrintSomething()
{
Console.WriteLine("Something");
}
}
class TestService(PrintService printService)
{
private CancellationTokenSource _cts;
private Task _task;
public void StartExecuting(CancellationToken cancellationToken = default)
{
_cts = new();
_task = Task.Run(async () =>
{
await DoWork(_cts.Token);
}, cancellationToken);
}
public void StopExecuting(CancellationToken cancellationToken = default)
{
_cts.Cancel();
_task.Wait(cancellationToken);
}
public async Task DoWork(CancellationToken cancellationToken)
{
while (true)
{
try
{
Console.WriteLine("Doing work");
printService.PrintSomething();
await Task.Delay(1000, cancellationToken);
} catch (OperationCanceledException)
{
Console.WriteLine("Operation cancelled");
break;
}
}
}
}