相关疑难解决方法(0)

名为Mutex等待

因此我不能使用线程仿射锁async- 如何在运行多个进程时保护我的资源?

例如,我有两个使用以下任务的进程:

 public async Task<bool> MutexWithAsync()
 {
     using (Mutex myMutex = new Mutex(false, "My mutex Name"))
     {
         try
         {
             myMutex.WaitOne();
             await DoSomething();
             return true;
         }
         catch { return false; }
         finally { myMutex.ReleaseMutex(); }
     }
 }
Run Code Online (Sandbox Code Playgroud)

如果由Mutex保护的moethod是同步的,那么上面的代码将起作用,但async我会得到:

从不同步的代码块调用对象同步方法.

Named Mutex对异步代码没用吗?

c# multithreading asynchronous async-await

15
推荐指数
2
解决办法
8583
查看次数

废弃的命名信号量未释放

当 C# 程序持有命名信号量时,如果应用程序提前终止(例如通过按 Ctrl+C 或关闭控制台窗口),它似乎不会被释放。至少在进程的所有实例都终止之前不会。

在这种情况下,使用命名互斥量会引发 AbandonedMutexException,但不会引发信号量。当另一个程序实例提前终止时,如何防止一个程序实例停顿?

class Program
{
    // Same with count > 1
    private static Semaphore mySemaphore = new Semaphore(1, 1, "SemaphoreTest");

    static void Main(string[] args)
    {
        try
        {
            // Blocks forever if the first process was terminated
            // before it had the chance to call Release
            Console.WriteLine("Getting semaphore");
            mySemaphore.WaitOne();  
            Console.WriteLine("Acquired...");
        }
        catch (AbandonedMutexException)
        {
            // Never called!
            Console.WriteLine("Acquired due to AbandonedMutexException...");
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex);
        }

        Thread.Sleep(20 * 1000);
        mySemaphore.Release();
        Console.WriteLine("Done");
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# semaphore

7
推荐指数
1
解决办法
4150
查看次数

标签 统计

c# ×2

.net ×1

async-await ×1

asynchronous ×1

multithreading ×1

semaphore ×1