gpt4 book ai didi

c# - .NET : Using Mutex to make sure a webservice is only called once at a time

转载 作者:行者123 更新时间:2023-11-30 14:20:41 25 4
gpt4 key购买 nike

我正在使用 Mutex 来确保 Web 服务一次只运行一次,但我无法通过 WaitOnce 和 ReleaseMutex 使其 100% 正确。

我有这个:

    private static Mutex mutex = new Mutex();

[WebMethod]
public bool TriggerAll()
{
bool ranJobs = false;
try
{
if (mutex.WaitOne(0, false))
{
Thread.Sleep(10000); // simulate a long operation
ranJobs = true;
}
}
finally
{
mutex.ReleaseMutex();
}
return ranJobs;
}

我尝试立即访问 Web 服务两次,第二次调用没有返回 false,但我从 mutex.ReleaseMutex 得到了一个 ApplicationException(“objectsyncronization 方法是从一个 onsyncronized codeblock 调用的”——大致翻译自瑞典语)

执行此操作的最佳方法是什么?

最佳答案

无论您的 WaitOne 是否返回 true,您都在调用 ReleaseMutex。如果你设法获得它,你应该只调用 ReleaseMutex:

    if (mutex.WaitOne(0, false))
{
try
{
Thread.Sleep(10000); // simulate a long operation
ranJobs = true;
}
finally
{
mutex.ReleaseMutex();
}
}

顺便问一下,您的互斥量是否被多个进程或 AppDomains 使用?否则,普通的 CLR 监视器(使用 Monitor.TryEnter)会更轻。

关于c# - .NET : Using Mutex to make sure a webservice is only called once at a time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/970217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com