简体   繁体   English

有人可以给我一个如何在C#中使用System.Monitor的简单示例吗?

[英]Please can someone give me a simple example of how to use System.Monitor in C#?

I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz. 我发现System.Monitor非常令人困惑,虽然我理解线程,锁,死锁,竞争条件,餐饮哲学家和所有爵士乐。 Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient. 通常我使用ManualResetEvent()来进行线程间协调,但我知道这是一个重量级的内核对象,System.Monitor(Enter / Pulse等)效率更高。 I've Googled and Googled but cannot find a sensible example. 我用谷歌搜索和谷歌搜索,但找不到一个明智的例子。

I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-) 如果SO工作人员可以向我解释这个可能很棒的构造,我将非常感激:-)

Here's a very simple example; 这是一个非常简单的例子; the call to Wait releases the lock (allowing Worker to obtain it) and adds the Main thread to the lock-object's pending queue. Wait的调用释放锁(允许Worker获取它)并将Main线程添加到lock-object的挂起队列中。 Worker then obtains the lock, and calls Pulse : this moves the Main thread into the lock-object's ready queue. 然后, Worker获取锁定,并调用Pulse :这会将Main线程移动到lock-object的就绪队列中。 When Worker releases the lock, Main can resume work. Worker 释放锁时, Main可以恢复工作。

Note that lock(obj) {...} is just compiler-candy for Monitor.Enter / Monitor.Exit in a try/finally block. 请注意, lock(obj) {...}只是try / finally块中Monitor.Enter / Monitor.Exit编译器。

[edit: I changed the sample to move lock(sync) earlier, to avoid the (unlikely) risk of a missed Pulse] [编辑:我之前更改了示例以移动lock(sync) ,以避免错过Pulse的(不太可能)风险]

    static void Main()
    {
        object sync = new object();
        lock (sync)
        {
            ThreadPool.QueueUserWorkItem(Worker, sync);
            Console.WriteLine("Main sleeping");

            // wait for the worker to tell us it is ready
            Monitor.Wait(sync);
            Console.WriteLine("Main woke up!");
        }
        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }
    static void Worker(object sync)
    {
        Console.WriteLine("Worker started; about to sleep");
        Thread.Sleep(5000);
        Console.WriteLine("Worker about pulse");
        lock (sync)
        { // notify Main that we did something interesting
            Monitor.Pulse(sync);
            Console.WriteLine("Worker pulsed; about to release lock");
        }
        Console.WriteLine("Worker all done");
    }

See if this part of my threading article helps... (the second half of that page). 看看我的线程文章的这一部分是否有帮助......(该页面的后半部分)。 It implements a producer/consumer queue: when the producer produces something in the queue (and finds it was empty - as an optimisation), it pulses the monitor to wake up any waiting threads. 它实现了一个生产者/消费者队列:当生产者在队列中生成某些东西(并发现它是空的 - 作为优化)时,它会激活监视器以唤醒任何等待的线程。 When a consumer tries to consume from the queue but finds it empty, it waits for a pulse before trying again. 当消费者尝试从队列中消耗但发现它为空时,它会在再次尝试之前等待一个脉冲。

Alternatively, Joe Albahari's threading tutorial has a section on Wait/Pulse too. 或者, Joe Albahari的线程教程也有一个关于Wait / Pulse的部分。

It's quite similar to the WaitHandle stuff you're used to - although frankly I find it easier to get my head round than WaitHandles, mostly because it's so similar to the Java wait/notify that I "grew up" with :) 它与你习惯使用的WaitHandle非常相似 - 虽然坦率地说我发现比WaitHandles更容易让人头脑发热,主要是因为它与Java等待/通知类似,我“长大”了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我使用“显示器”时,因为不能用“锁定”来完成,您能举一个简单的例子吗? - Can you give me a simple example when I am to use “monitor” because it cannot be done with “lock”? 请给我一个C#中隐式和显式类型转换的例子 - Please give me example of implicit and explicit type conversion in C# 有人可以向我解释 C# 8 可为空的引用类型吗? - Can someone please explain C# 8 nullable reference type to me? 有人可以向我解释设置以及如何在C#中使用它们吗? - Can someone explain Settings to me and how to use them in C#? 不确定使用 lambdas 处理这个 c# 事件是如何工作的,有人可以向我解释一下吗? - Not sure how this c# event handling with lambdas work, can someone explain it to me please? 系统使用的简单示例。 计时器。 C#中的定时器 - Simple example of the use of System. Timers. Timer in C# 有人可以解释一下 <Func<T, bool> &gt;对我来说很简单 - Can someone please explain the <Func<T, bool>> in a simple way for me 我如何在 C# 中执行它有人可以帮助我 - how can i execute this in C# can someone help me 在此特定示例(IP地址表达式)中,有人可以帮助我比较使用F#和C#吗? - Can someone help me compare using F# over C# in this specific example (IP Address expressions)? 有人可以告诉我如何在C#上修复此错误 - Can someone tell me how to fix this error on C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM