0

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.

Theodor Zoulias
  • 24,585
  • 5
  • 40
  • 69
Lenny
  • 25
  • 4
  • 1
    The cancellation in .NET [is cooperative](https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads). If you want to cancel some ongoing work in a non-cooperative fashion, you are in trouble. The [`Thread.Abort`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.abort) method is no longer supported in .NET. If you invoke it on .NET 5 or .NET Core, all you get is a `PlatformNotSupportedException`. – Theodor Zoulias Jul 10 '21 at 11:34

0 Answers0