Home > front end >  How to change a variable inside a thread? C#
How to change a variable inside a thread? C#

Time:12-12

I'm trying to do animations with WinForms, I'm doing my own methods for animating using PNG sequence, if you have a better way of doing it, let me know

So I have a method that starts a thread, and returns it:

Thread thread = new Thread(()=> SomeFunction(SomeParameter));
thread.Start();

return thread;

Now I want to access that thread's variables and change them.

void SomeFunction(String Parameter)
{
    Boolean iWantToChangeThisVariable = true;
}

For example, I want to access this 'iWantToChangeThisVariable' and set it to false while the thread is still running.

Is that possible?

CodePudding user response:

If your primary goal is to stop an asynchronous task, you should use a CancellationTokenSource object like in the following example

This code runs an asynchronous task (the Test method) that writes to the console every second, and then it stops it after five seconds

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;
            Task.Run(() => Test(cancellationToken));
            Task.Delay(5000).Wait();
            cancellationTokenSource.Cancel();
        }

        async static Task Test(CancellationToken cancellationToken)
        {
            while (true)
            {
                try
                {
                    Console.WriteLine("The task is running");
                    await Task.Delay(1000, cancellationToken);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
            }
        }

    }
}

CodePudding user response:

I didn't find an exact answer, but I found even better enlightenment; I'm moving to WPF instead of WindowsForms, since it's using GPU to render things, rather than CPU, and has in-built support for animations. Maybe this answer will help someone.

  • Related