为什么ApplicationException的被抛出?(Why ApplicationExcept

2019-09-16 23:14发布

我只是尝试对互斥和写了下面的代码。

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块中得到这个。

Answer 1:

您正在释放互斥即使你的WaitOne失败。 移动,你知道你已经获得了互斥的if语句里面的ReleaseMutex电话。



Answer 2:

@约翰的回答是正确的,但对子孙后代,我认为更好的方式是设置一个布尔值是在真if之后,还做releasefinally块,但这次只有这样做,如果布尔是真实的。 问题是,如果任何的if从句则抛出互斥量将不会被释放。 我想你会在增加更多if条款不只是写和睡眠。

你总是想用一个try { ... } finally ,如果你能模式,而只是防止了waitOne()调用返回false。 像下面这样:

bool release = false;
try {
    if (mut.waitOne(time)) {
        release = true;
        ...
    } else {
        ...
    }
} catch (AbandonedMutexException ex) {
    ...
} finally {
    ...
    if (release) {
        mut.ReleaseMutex();
    }
}


文章来源: Why ApplicationException is thrown?