比如C# 中的lock(){}代码,多线程调用时,有一个线程在使用了,其他线程就会等待。
但是我有一个需求,A、B、C 3个线程共同竞争一个函数Test(),谁先抢到归谁,其他2个线程发现已有线程在使用这个函数,直接放弃调用。
C#中有没有这种写法啊,多线程不等待直接放弃
C# 如何做到多线程阻塞后不等待直接放弃
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
threenewbee 2023-07-23 20:55关注用 Monitor:
using System; using System.Threading; class Program { static object lockObject = new object(); static void Main(string[] args) { Thread threadA = new Thread(Test); Thread threadB = new Thread(Test); Thread threadC = new Thread(Test); threadA.Start("A"); threadB.Start("B"); threadC.Start("C"); threadA.Join(); threadB.Join(); threadC.Join(); } static void Test(object threadName) { if (Monitor.TryEnter(lockObject)) { try { Console.WriteLine($"Thread {threadName} acquired the lock."); // 执行需要互斥的代码 } finally { Monitor.Exit(lockObject); } } else { Console.WriteLine($"Thread {threadName} skipped the call."); } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用