How can I wait for a thread to finish with .NET?

前端 未结 10 2246
有刺的猬
有刺的猬 2020-11-22 10:27

I\'ve never really used threading before in C# where I need to have two threads, as well as the main UI thread. Basically, I have the following.

public void S         


        
10条回答
  •  轮回少年
    2020-11-22 10:53

    The previous two answers are great and will work for simple scenarios. There are other ways to synchronize threads, however. The following will also work:

    public void StartTheActions()
    {
        ManualResetEvent syncEvent = new ManualResetEvent(false);
    
        Thread t1 = new Thread(
            () =>
            {
                // Do some work...
                syncEvent.Set();
            }
        );
        t1.Start();
    
        Thread t2 = new Thread(
            () =>
            {
                syncEvent.WaitOne();
    
                // Do some work...
            }
        );
        t2.Start();
    }
    

    ManualResetEvent is one of the various WaitHandle's that the .NET framework has to offer. They can provide much richer thread synchronization capabilities than the simple, but very common tools like lock()/Monitor, Thread.Join, etc.

    They can also be used to synchronize more than two threads, allowing complex scenarios such as a 'master' thread that coordinates multiple 'child' threads, multiple concurrent processes that are dependent upon several stages of each other to be synchronized, etc.

提交回复
热议问题