C#中的锁定代码部分 [英] Lock code section in c#

查看:61
本文介绍了C#中的锁定代码部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题在这里听起来可能与许多其他问题一样,但是却有我找不到的味道.

我正在尝试理解以下逻辑

通用对象

 公共类GenericClass{公共静态void DoSomething(Object lockObj){锁(lockObj){//在这里做点事}}} 

A级

 内部A类{私人静态_aLock = new Object();公共无效Do_A_Thing(){GenericClass.DoSomething(_aLock);}} 

B级

 内部类B{私人静态_bLock = new Object();公共无效Do_B_Thing(){GenericClass.DoSomething(_bLock);}} 

我只是希望确认我的解释是否正确:

如果"A"类的多个线程将尝试同时访问"genericClass"方法"DoSomething"中的代码,则该方法将被锁定到除"A"类的一个实例之外的所有实例上.但是,类"B"的单个实例将能够随时执行.如果"B"类还将执行多个实例,那么它们将不会干扰"A"类的锁.

根据您在上面看到的内容,这正确吗?

解决方案

是的,您的描述听起来正确.传递锁对象 in 也许有点不寻常,但是可以正常工作.我建议的唯一更改是将 static 字段设置为 readonly ,以便您不会意外地将值更改为其他 object 引用./p>

My question may sound like many others here but it has a flavor I didn't find.

I am trying to understand the following logic

A generic object

public class GenericClass
{
    public static void DoSomething(Object lockObj)
    {
        lock(lockObj)
        {
            // do something here
        }
    }
} 

Class A

internal class A
{
    private static _aLock = new Object();

    public void Do_A_Thing()
    {
        GenericClass.DoSomething(_aLock);
    }
} 

Class B

internal class B
{
    private static _bLock = new Object();

    public void Do_B_Thing()
    {
        GenericClass.DoSomething(_bLock);
    }
} 

I just hope to confirm if my explanation is correct:

If multiple threads of class "A" will attempt simultaneously access code in "genericClass" method "DoSomething", this method will be locked to all but one instance of class "A". But a single instance of class "B" will be able to proceed with execution any time. If class "B" will also have multiple instances execute, they will not interfere with class "A" locks.

Is this correct based on what you see above?

解决方案

Yes, your description sounds correct. It is perhaps a little unusual to pass the lock object in, but it'll work fine. The only change I would suggest is to make the static fields readonly so you can't accidentally change the value to a different object reference.

这篇关于C#中的锁定代码部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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