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; }