问题描述
限时送ChatGPT账号..我在多线程应用程序中有一个方法,我希望在调用此方法时有以下行为:
I have a method in a multi-threaded application and I'd like the following behavior when this method is invoked:
如果当前没有其他线程正在执行该方法,则执行它.如果另一个线程当前正在执行该方法,则退出该方法而不执行它.C# 中的 lock
语句对于等待线程完成执行很有用,但我不想序列化对此方法的访问,而是绕过执行该方法(如果它正在被执行)另一个线程.
The lock
statement in C# is useful for waiting until a thread has completed execution, but I don't want to serialize access to this method but rather bypass executing said method if it is being executed by another thread.
推荐答案
我想我不明白......如果一次只能由一个线程调用,为什么多个线程开始调用它?
I suppose I don't understand... if it should only be called by one thread at a time, why are multiple threads calling it to begin with?
无论如何,您可以使用 Monitor.TryEnter().如果无法获取锁,它不会阻塞并返回 false
.在这种情况下,您可以直接从函数中返回.
Anyway, you can use Monitor.TryEnter(). It doesn't block and returns false
if it fails to acquire a lock. In that case you can just return from the function.
这篇关于如果另一个线程正在执行一个方法,则退出该方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论