简体   繁体   English

当我使用“显示器”时,因为不能用“锁定”来完成,您能举一个简单的例子吗?

[英]Can you give me a simple example when I am to use “monitor” because it cannot be done with “lock”?

MSDN tells me that using lock is equivalent to using monitor but is more concise and less error prone . MSDN告诉我,使用锁等效于使用监视器, 但更简洁,更不易出错

Can you give me a simple (single process) example why would I be forced to use Monitor because it cannot be done with lock ? 您能给我一个简单的(单个过程)示例,为什么由于无法使用lock来强制我使用Monitor

Can you give me a simple (single process) example why would I be forced to use monitor when the lock is not enough? 您能给我一个简单的(单个过程)示例,为什么在锁不够时为什么会强制使用Monitor?

Sure. 当然。 Suppose you want to take an action if you can acquire the lock, but if some other object already owns it, you don't want to block for longer than a certain time: 假设您想采取行动, 如果可以获取该锁,但是如果某个其他对象已经拥有该锁,则您不想阻塞的时间超过一定时间:

bool gotMonitor = false;

try
{
    Monitor.TryEnter(monitor, 500, ref gotMonitor);
    if (gotMonitor)
    {
        // Okay, we're in the lock. We can do something useful now.
    }
    else
    {
        // Timed out - do something else
    }
}
finally
{
    if (gotMonitor)
    {
        Monitor.Exit(monitor);
    }
}

(Note that I'm deliberately not using the overload of TryEnter which just returns success/failure - the version I'm using is more reliable, as the setting of the ref parameter is atomic with respect to the lock acquisition.) (请注意,我故意 使用TryEnter的重载,后者仅返回成功/失败 -我使用的版本更可靠,因为ref参数的设置相对于锁获取而言是原子的。)

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

相关问题 有人可以给我一个如何在C#中使用System.Monitor的简单示例吗? - Please can someone give me a simple example of how to use System.Monitor in C#? 可以举个例子,说明何时应该使用UIElement.UpdateLayout()? - Can give me an example that when should use UIElement.UpdateLayout()? 你能给我一个在.NET中导致内存碎片的例子吗? - Can you give me an example that causes memory fragmentation in .NET 我应该使用GDI +还是可以通过简单的方式完成 - Should I use GDI+ or it can be done in a simple way 我用离子api和我面临一些问题。你能解释一下我们如何在离子中使用api吗? - I am used api with ionic and i face some issue about that .can you please explain me how we use the api in ionic? C#:谁能给我一个很好的例子,说明如何在运行时锚定控件? - C#: Could anyone give me good example on how anchoring controls at runtime is done? 任何人都可以通过示例给我Dotnetnuke模块本地化 - Can any one give me Dotnetnuke module localization with example C# 只读不改队列是否应该使用lock语句? - C# Should I use lock statement when I am only reading and not changing queue? 你能帮我解决这个跳跃的 animation 代码吗?我遇到了麻烦 - Can you help me with this jumping animation code I am having trouble with it 你如何找到锁的所有者(监视器)? - How do you find the owner of a lock (Monitor)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM