[C#]多个线程的等待

2020/04 26 20:04
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class ThreadTestProj : MonoBehaviour
{
    [ContextMenu("开始执行")]
    void StartExecute()
    {
        Debug.Log("PrepareExecute");
        var waits = new List<EventWaitHandle>();
        for(int i=0; i<2; ++i)
        {
            var mr = new ManualResetEvent(false);
            waits.Add(mr);
            Thread thread = new Thread(ExecuteThreadBody);
            thread.Start(mr);
        }
        Debug.Log("WaitAll...");
        WaitHandle.WaitAll(waits.ToArray());
        Debug.Log("Execute.Finish");
    }

    void ExecuteThreadBody(object obj)
    {
        ManualResetEvent p = obj as ManualResetEvent;
        Thread.Sleep(3000);
        Debug.Log("Body.Execute"); // 这句可能会卡死!
        p.Set();
    }
}

输出为:

PrepareExecute
Body.Execute
Body.Execute
WaitAll…
Execute.Finish

在子线程中,不要操作任何Unity对象,包括日志输出