I've been tinkering through some stuff, and this code sample made me wonder - should I implement the StopCalculation
method with a Task, or the way it's been done is perfectly okay, and actually recommended?
Thanks!
public class TesterSeventeen : MemoryStream
{
Task task;
bool stopper;
public TesterSeventeen() : base()
{
task = new Task(() =>
{
while (!stopper)
{
Console.WriteLine("Generate work.");
Thread.Sleep(2000);
}
});
}
public void StartCalculation()
{
task.Start();
}
public bool IsTaskDisposed()
{
return task.IsCompleted;
}
public void StopCalculation()
{
new Thread(() =>
{
Console.WriteLine("***Doomsday thread started.***");
Console.WriteLine(task.Status);
stopper = true;
task.Wait();
task.Dispose();
Console.WriteLine(task.Status);
Console.WriteLine("***Doomsday thread brought apocalypse.***");
}).Start();
}
}
class Program
{
static async Task Main(string[] args)
{
using (var mem = new TesterSeventeen())
{
mem.StartCalculation();
Thread.Sleep(100);
mem.StopCalculation();
}
// Even though we've exited the using block, the thread will continue its work
while (true)
{
// Manually exit program, after observations
Console.WriteLine("hm");
Thread.Sleep(100);
}
}