0

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

Harshal Valanda
  • 5,331
  • 26
  • 63

1 Answers1

0

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.

gmiley
  • 6,531
  • 1
  • 13
  • 25