gpt4 book ai didi

c# - 为什么会抛出 ApplicationException?

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:36 25 4
gpt4 key购买 nike

我只是在 Mutex 上进行试验并编写了以下代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Mutex_WaitOnewithTimeouts
{
class Program
{
private static Mutex mut = new Mutex();
private static int numOfThreads = 5;
private static int numOfIterations = 3;
private static Random rand = new Random();

static void Main(string[] args)
{
Thread[] threads = new Thread[5];
for (int num = 0; num < numOfThreads; num++)
{
threads[num] = new Thread(new ThreadStart(MyThreadProc));
threads[num].Name = String.Format("Thread{0}", num);
threads[num].Start();
}
Console.Read();
}

private static void MyThreadProc()
{
for (int iteration = 0; iteration < numOfIterations; iteration++)
{
UseResource();
}
}

private static void UseResource()
{
Console.WriteLine("{0} accessing ", Thread.CurrentThread.Name);
int time = (int)(rand.NextDouble() * 100);
try
{
if (mut.WaitOne(time))
{
Console.WriteLine("Yippie got mutex for {0}", Thread.CurrentThread.Name);
Thread.Sleep((int)rand.NextDouble() * 5000);
}
else
{
Console.WriteLine("Nopee.... Timeout occured for {0}", Thread.CurrentThread.Name);
}
}
catch (AbandonedMutexException ex)
{
Console.WriteLine(" Exception is caught");
}
finally
{
Console.WriteLine("Releasing mutex for {0}", Thread.CurrentThread.Name);
mut.ReleaseMutex();

}

}
}
}

但我有时会收到 ApplicationException。如果我的代码有任何问题,有人可以帮助我吗,还请解释何时会触发此异常。

从未同步的代码块调用了对象同步方法。尝试释放互斥锁时,我在 finally block 中得到了这个。

最佳答案

即使 WaitOne 失败,您也正在释放互斥量。将 ReleaseMutex 调用移动到您知道已获得互斥锁的 if 语句中。

关于c# - 为什么会抛出 ApplicationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402464/

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