Usage of Mutex in c#

后端 未结 4 2039
陌清茗
陌清茗 2020-12-15 03:23

I am a bit new in threading in c# and on general, in my program I am using mutex to allow only 1 thread getting inside a critical section and f

4条回答
  •  盖世英雄少女心
    2020-12-15 04:06

    The problem here is that all your callers are using a different mutex; you need the locking object to be shared, usually by making it a field. For example, and switching to a simpler lock metaphor:

    private readonly object syncLock = new object();
    public void ThreadSafeMethod() {
        lock(syncLock) {
            /* critical code */
        }
    }
    

    or using the mutex:

    private readonly Mutex m = new Mutex();
    public void ThreadSafeMethod() {
        m.WaitOne();
        try {
            /* critical code */
        } finally {
            m.ReleaseMutex();
        }
    }
    

提交回复
热议问题