Mutex和IDisposable的麻烦 [英] Troubles with Mutex and IDisposable

查看:68
本文介绍了Mutex和IDisposable的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!



遇到特定问题。我创建了一个IDisposable类,允许我锁定两种方法之间的打开/关闭端口



Hi, everybody!

Have a specific trouble. I've created a IDisposable class allows me to lock Open/Close port between two methods

 public class SerialWrap:IDisposable
 {
        private SerialPort _serialPort;

        private static Mutex _mutex = new Mutex();

        public SerialWrap(SerialPort serialPort)
        {
            _mutex.WaitOne();

            _serialPort = serialPort;

            if (!_serialPort.IsOpen)
            {
              _serialPort.Open();
            }
            else
            {
                 Logger.Error("Serial Port had been opened YET!");
            }

        }


        public void Dispose()
        {
            try
            {
                if (_serialPort.IsOpen)
                    _serialPort.Close();

            }
            catch (Exception){ }
            
            try
            {
                 _mutex.ReleaseMutex();
            }
            catch (Exception e){  Logger.Error(e.Message); throw;}

        }
}







代码中的任何地方我都使用声明使用它来表示






Everywhere in code i use using statement for it

using(new SerialWrap(_serialPort))
{
     // any code...
}





我收到一些礼物错误



调用线程不拥有互斥锁。



为什么会发生这样的事情以及可以抛出的地方?

请帮忙!



In some sitation i receive an error

The calling thread does not own the mutex.

Why did so happen and where it can be thrown?
Any help please!

推荐答案

问题是在中释放互斥锁IDisposable.Dispose 。从来没有这样做过。应该采用互斥锁并保证在相同的上下文中在短时间内释放互斥锁,以同步对某些共享资源的访问。为什么?为什么不做你在做什么?这在快速解答中解释太久了,但这是线程的基础知识之一。要了解相关信息,请仔细阅读:

http://en.wikipedia.org/wiki/Mutual_exclusion [ ^ ]。



-SA
The problem is releasing the mutex in IDisposable.Dispose. Never ever do it. Mutex should be taken and guaranteed to be released in a short period of time in the same context, to synchronize access to some shared resource. Why? Why not doing what you are doing? This is too long to explain in a Quick Answer, but this is one of the very basics of threading. To get an idea, please read carefully:
http://en.wikipedia.org/wiki/Mutual_exclusion[^].

—SA


这篇关于Mutex和IDisposable的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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