I want a function that runs infinitely until I tell it to stop, and I also want to be able to start it again.
My attempt looked something like this:
namespace Infinite_print_button
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// button will infinitely do a thing until told to stop
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private CancellationTokenSource cancellationToken;
private async void Print()
{
try
{
Task.Factory.StartNew(() =>
{
while (true)
{
Console.WriteLine("asdf");
}
}, cancellationToken.Token);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void test_Click(object sender, RoutedEventArgs e)
{
if (cancellationToken != null)
{
Console.WriteLine("off");
cancellationToken.Cancel();
cancellationToken = null;
}
else
{
Console.WriteLine("on");
cancellationToken = new CancellationTokenSource();
Print();
}
}
}
}
It starts Ok but when I try and stop it it does not stop and make the whole program freezes up.
Thread.Start() and Thread.Abort() also break it.
I'm new to C#, so I'm hoping I'm making a simple mistake.