为什么ApplicationException的被抛出? [英] Why ApplicationException is thrown?

查看:1211
本文介绍了为什么ApplicationException的被抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试对互斥,写了下面的code。

I am just experimenting on Mutex and wrote the following code.

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的有时..有人可以帮我,如果有什么问题我的code,也请解释时,将这个异常的触发。

But I am getting ApplicationException sometimes.. Can someone please help me if there is anything wrong with my code and also please explain when will this exception trigger.

对象的同步方法从code非同步块中调用。我试图释放互斥锁时得到这个finally块。

Object synchronization method was called from an unsynchronized block of code. I am getting this in the finally block when trying to release the mutex.

推荐答案

正在释放,即使你失败的WaitOne互斥。移动ReleaseMutex调用的if语句,你知道你已经获得了互斥体。

You are releasing the mutex even if your WaitOne failed. Move the ReleaseMutex call inside the if statement where you know you have the mutex obtained.

这篇关于为什么ApplicationException的被抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆