marhyno
marhyno

Reputation: 699

Starting and Stopping loop from thread c#

so this is a big deal I need to solve. I have my Visual C# application. In this application users enter data and click execute. When they click execute the core method starts in new thread, in that thread and method is one loop. Constantly using Method invoker I am sending updates to the UserForm what the loop is actually doing. e.g. Like this I am updating progressBar in every cicle.

progressBar1.Invoke((MethodInvoker) delegate { progressBar1.Value += 1; });

I got the requirement to add a button in UserForm which stops the loop in that thread and shows what has been done yet. Not quiting application not stopping processes or what ever I only need to jump to that thread and stop the loop.

I was thinking to add a public class with public methods called stop_loop.cs. I was hoping that when I start the program or execute the core method in new thread It will jump to that class and set cancel to = false, and if I click on the stop button it will also jump to that class and set cancel to true. In the end at the beggining of every cicle in that loop in that thread it will check if cancel is true. If it is, than it will stop loop and move to the end of the execution.

Like this. Unfortunately I cannot seem to access this class from my core function. Not even Visual Studio is offering me this option. How can I do it ?

namespace textboxes
{
    public class stop_loop
    {
        public bool is_canceled;

        public void set_canceled(bool state)
        {
            this.is_canceled = state;
        }
        public bool get_canceled()
        {
            return this.is_canceled;
        }
    }
}

Upvotes: 0

Views: 1380

Answers (1)

ashchuk
ashchuk

Reputation: 331

You should use CancellationToken. Here is a sample with calculating factorial:

static void Main(string[] args)
{
    CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
    CancellationToken token = cancelTokenSource.Token;

    Task task1 = new Task(async () => await Factorial(5, token));
    task1.Start();

    Console.WriteLine("Type Y to break the loop:");
    string s = Console.ReadLine();
    if (s == "Y")
        cancelTokenSource.Cancel();

    Console.ReadLine();
}

static async Task Factorial(int x, CancellationToken token)
{
    int result = 1;
    for (int i = 1; i <= x; i++)
    {
        if (token.IsCancellationRequested)
        {
            Console.WriteLine("Canceled");
            return;
        }

        result *= i;
        Console.WriteLine("Factorial of {0} equals {1}", i, result);
    }
}

Upvotes: 3

Related Questions