比如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无用
悬赏问题
- ¥17 pro*C预编译“闪回查询”报错SCN不能识别
- ¥15 微信会员卡接入微信支付商户号收款
- ¥15 如何获取烟草零售终端数据
- ¥15 数学建模招标中位数问题
- ¥15 phython路径名过长报错 不知道什么问题
- ¥15 深度学习中模型转换该怎么实现
- ¥15 Stata外部命令安装问题求帮助!
- ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
- ¥15 TYPCE母转母,插入认方向
- ¥15 如何用python向钉钉机器人发送可以放大的图片?