简体   繁体   English

暂停控制器方法调用C#上的线程

[英]Pause a thread on a controller method call C#

My Question is about C# Threading. 我的问题是关于C#线程的。

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. .Net有很多线程同步类/方法,您可以进一步研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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