C#lock语句,锁定哪些对象? [英] C# lock statement, what object to lock on?

查看:467
本文介绍了C#lock语句,锁定哪些对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个问题,我需要帮助。

I have 3 questions that I need help with.


  1. 什么是正确的对象/引用为锁定语句的参数传递?我已经看到了很多样品codeS和我注意到,传递的对象/引用也可能会被不相关的当前类或程序中​​的任何其它类只要访问修饰符静态非公开?例如:

  1. What are the correct objects/references to be passed as lock statement parameter? I've seen a lot of sample codes and I noticed that the objects/references passed in could possibly be non related to the current class or any other class in the program as long as the access modifier static is non public? E.g.:

private Object anyObj = new Object();
lock(anyObj){.....}

private static readonly object Locker = new object();
lock(Locker){.....}

这只是没有任何意义了我。

It just doesn't make sense to me.

我发现在MSDN中关于多线程的样本code,使用锁定语句了。在样本有两个尝试 / Monitor.Wait()捕获在其中。如果我理解正确的逻辑, readerFlag 将禁止程序不断进入尝试 / 块都
的code是这里的例子2:

http://msdn.microsoft.com/en-美国/库/ aa645740(v = vs.71)的.aspx

I found a sample code in MSDN about multi threading that uses lock statements too. In the sample there are two try/catch blocks with the Monitor.Wait() within it. If I understand the logic correctly, the readerFlag will forbid the program to ever enter the try/catch block at all.
The code is example 2 from here:
http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

我如何运行在后台,只要Windows窗体是活动的运行一个线程?

How do I run a thread that runs in the background as long as the Windows Form is active?

谁能帮助我吗?我已经冲刷了很多很多小时在网上,我无法得到我想要的答案。

Can anyone help me please? I've been scouring the web for many many hours and I can't get the answer I wanted.

推荐答案

如何与您锁定什么取决于你在做什么。

How and what you lock on depends upon what you're doing.

让我们说,你与某种设备的工作 - 比如一个咖啡壶。你可能有一个类,它看起来像这样:

Let's say that you're working with a device of some kind - say a coffee maker. You might have a class that looks like this:

public CoffeeMaker {
    private IntPtr _coffeeHandle;
    private Object _lock = new Object();
}

在这种情况下,你要保护访问_coffeeHandle - 指针/句柄真实的物理设备,所以这是pretty容易:

In this case, you are protecting access to the _coffeeHandle - a pointer/handle to a real physical device, so this is pretty easy:

public int AvailableCups {
    get {
        lock (_lock) {
            return GetAvailableCups(_coffeeHandle); // P/Invoked
        }
    }
}

public void Dispense(int nCups)
{
    lock (_lock) {
        int nAvail = GetAvailableCups(_coffeeHandle);
        if (nAvail < nCups) throw new CoffeeException("not enough coffee.");
        Dispense(_coffeeHandle, nCups); // P/Invoked
    }
 }

所以,如果我运行一个多线程的应用程序,我(可能)不希望阅读可用,而我配药杯数(也许这是一个硬件错误)。通过保护访问到手柄,我可以保证。另外,我不能问,而我已经分配分配 - 这将是坏的,所以这是保护了。最后,我不分配,除非我有足够可用的咖啡,你注意到我的使用我的公共财产,检查 - 这种方式,确保行动有足够的咖啡和配送绑在一起。魔语是原子 - 他们不能在没有产生问题割裂

So if I'm running a multithreaded app, I (probably) don't want to read the number of cups that are available while I'm dispensing (maybe it's a hardware error). By protecting accesses to the handle, I can ensure that. Also, I can't be asked to dispense while I'm already dispensing - that would be bad, so that's protected too. Finally, I don't dispense unless I have enough coffee available and you notice that I don't use my public property to check that - this way the action of ensuring there's enough coffee and dispensing are tied together. The magic word is atomic - they can't be cut apart without creating issues.

您使用静态对象作为锁,如果你有一个且只有一个需要保护的资源的一个实例。想想,我有一个单身?这将是当你可能需要一个静态锁的指导方针。例如,让我们说,咖啡有一个私人的构造函数。相反,你有构建咖啡机工厂方法:

You use a static object as a lock if you have one and only one instance of a resource that needs protecting. Think, "do I have a singleton?" and that will be a guideline for when you might need a static lock. For example, let's say that CoffeeMaker has a private constructor. Instead, you have a factory method that constructs coffee machines:

static Object _factLock = new Object();

private CoffeeMaker(IntPtr handle) { _coffeeHandle = handle; }

public static CoffeeMaker GetCoffeeMaker()
{
    lock (_factLock) {
        IntPtr _handle = GetCoffeeMakerHandle(); // P/Invoked
        if (_handle == IntPtr.Zero) return null;
        return new CoffeeMaker(_handle);
    }
 }

现在在这种情况下,感觉就像咖啡应该实现IDisposable ,使手柄被照顾的,因为如果你不松开,然后有人可能不会得到他们的咖啡。

Now in this case, it feels like CoffeeMaker should implement IDisposable so that handle gets taken care of, because if you don't release it then somebody might not be getting their coffee.

有一些问题,但 - 也许,如果没有足够的咖啡,我们应该让更多的 - 而这需要很长的时间。哎呀 - 配药咖啡需要很长的时间,这就是为什么我们小心地保护我们的资源。现在,你在想真的这一切的咖啡壶的东西应该在它自己的线程,应该有咖啡时完成了被触发的事件,然后它开始变得复杂,你明白知道的重要性你锁定内容和具体时间,这样你就不会阻塞煮咖啡,因为你问了很多杯怎么在那里。

There are a few problems though - maybe if there's not enough coffee, we should make more - and that takes a long time. Heck - dispensing coffee takes a long time, which is why we're careful to protect our resources. Now you're thinking that really all this coffee maker stuff should be in a thread of its own and that there should be an event that gets fired when the coffee is done, and then it starts to get complicated and you understand the importance of knowing what you're locking on and when so that you don't block making coffee because you asked how many cups are there.

而如果加上僵局,原子,监控,等待和脉冲所有的声音陌生的你,你应该考虑在一般多/多线程读取,看看是否可以解决公平的理发店问题或的哲学家就餐问题,资源争夺的典型双方例子

And if the words "deadlock", "atomic", "monitor", "wait", and "pulse" all sound foreign to you, you should consider reading up on multiprocessing/multithreading in general and see if you can solve the fair barbershop problem or the dining philosophers problem, both quintessential examples of resource contention.

这篇关于C#lock语句,锁定哪些对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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