私はMutexを試していて、次のコードを書いています。なぜApplicationExceptionがスローされるのですか?
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をを取得しています。
コードの非同期ブロックからオブジェクト同期メソッドが呼び出されました。私はmutexをリリースしようとしたときにfinallyブロックでこれを取得しています。
例外からのラインの上のカップルを示し、それはあなたのサンプルコードでのスローされているもののラインを示すために、あなたの投稿を編集してください。 – Gray
'ApplicationException'はあなたがそれから派生した例外を個人的に作成したときにのみ見受けられます。あなたは見ている 'ApplicationException'ですか?あるいは、代わりに 'TargetInvocationException'や' WaitHandleCannotBeOpenedException'のような派生した例外がありますか? – user7116
例外のメッセージは何ですか?内部の例外はありますか?任意の手がかりのスタックトレースを見ましたか? – sellmeadog