简体   繁体   中英

Pause a thread on a controller method call C#

My Question is about C# Threading.

I want to pause a Thread on a controller method call.

I have a little idea that it can be done by joining our main thread from my already running thread to whom I want to pause until controller method completes its task.

Please Guide me the simplest way to do it.

Thanks

Probably one of the simpler ways would to use an indicator to signal if a thread should wait. Consider the following...

public class WaitTester
{
    public static bool _wait = false;

    public static void Initialize()
    {
        StartThreadOne(5);
        StartThreadTwo(5);
    }

    public static void StartThreadOne(int n)
    {
        new System.Threading.Tasks.Task(new Action<Object>((num) =>
            {
                Console.WriteLine("Thread1: == Start ========");
                int max = (int)num;
                for (int i = 0; i <= max; i++)
                {
                    while (_wait) { Thread.Sleep(100); }
                    Console.WriteLine("Thread1: Tick - {0}", i);
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Thread1: == End =========");
            }), n).Start();
    }

    public static void StartThreadTwo(int n)
    {
        new System.Threading.Tasks.Task(new Action<Object>((num) =>
            {
                Console.WriteLine("Thread2: == Start ========");
                _wait = true;
                int max = (int)num;
                for (int i = 0; i <= max; i++)
                {
                    Console.WriteLine("Thread2: Tick - {0}", i);
                    Thread.Sleep(1000);
                }
                _wait = false;
                Console.WriteLine("Thread2: == End =========");
            }), n).Start();
    }
}

This isn't the best way to handle cross threaded signalling, but is a very simple example of how it can be done. .Net has a whole host of thread synchronization classes/methods that you can look into further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM