const int TimeoutMs = 30; private static readonly ManualResetEventSlim _manualResetEvent = new ManualResetEventSlim(false); private static readonly object LockObj = new object(); static string GetInfoStr() { var rez = "超時"; Monitor.TryEnter(LockObj, TimeoutMs * 1000); try { //臨界區代碼 var random = new Random(); _ = Task.Run(() => { var newran = random.Next(100, 250); // Debug.WriteLine($"正常等待時間{newran}"); Thread.Sleep(newran); rez = $"正常執行{j}"; j++; _manualResetEvent.Set(); }); _manualResetEvent.Wait(TimeSpan.FromSeconds(TimeoutMs)); Debug.WriteLine("SpinCount:" + _manualResetEvent.SpinCount); _manualResetEvent.Reset(); } finally { Monitor.Exit(LockObj); } return rez; }