Skip to main content

How to lock a method - synchronized

Nu odată mi s-a întîmplat sa am nevoie sa sincronizez una sau mai multe metode din aceiași clasa.
In funcție de situație foloseam un cod asemănător cu cel de mai jos:
class ItemsStore
{
void AddItem(Item item)
{
lock(this)
{
...
}
}

void RemoveItem(Item item)
{
lock(this)
{
...
}
}

Item[] GetAvailableItemes()
{
lock(this)
{
...
}
}
}
Sunt cazuri când lock-ul se face pe un field sau pe un obiect diferit de this dintr-o alta clasa. Unu din dezavantaje care apare în acest caz este apariția a unui nou nivel de indentare.
Am descoperit un alt mecanism prin care se poate face lock automat pe metodele dorite. Deși exista din .NET 1.1 și cea mai mare parte din voi l-ați folosit deja, am considerat ca merita amintit.
Prin intermediul atributului MethodImpl putem specifica modul în care sa se facă lock-ul pentru fiecare metoda în parte( nu mai este nevoie sa folosim lock sau SyncLock) și nu numai. Prin acest atribut putem de fapt sa specificam de fapt modul în care o metoda se implementează.
Codul scris mai sus îl putem rescrie în forma următoare:
class ItemsStore
{
[MethodImpl(MethodImplOptions.Synchronized)]
void AddItem(Item item) { ... }

[MethodImpl(MethodImplOptions.Synchronized)]
void RemoveItem(Item item) { ... }

[MethodImpl(MethodImplOptions.Synchronized)]
Item[] GetAvailableItemes() { ... }
}
Personal cred ca în felul acesta codul devine mai ușor de înțeles si mai clar. Cea ce trebuie avut grija este ca MethodImplOptions.Synchronized face lock pe obiect și nu în toate cazurile avem nevoie de acest lucru.
Enumul MethodImplOptions ne permite sa setam următoarele stări pe care le putem combina:
  • Unmanaged - Specifies that the method is implemented in unmanaged code.
  • ForwardRef - Specifies that the method is declared, but its implementation is provided elsewhere.
  • PreserveSig - Specifies that the method signature is exported exactly as declared.
  • InternalCall - Specifies an internal call. An internal call is a call to a method that is implemented within the common language runtime itself.
  • Synchronized - Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, whereas instance methods lock on the instance. Only one thread can execute in any of the instance functions, and only one thread can execute in any of a class's static functions.
  • NoInlining - Specifies that the method cannot be inlined.
  • NoOptimization - Specifies that the method is not optimized by the just-in-time (JIT) compiler or by native code generation (see Ngen.exe) when debugging possible code generation problems.
Sursa: http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx

Enjoy it.

Comments

  1. lock(this) - depinde foarte mult de ce ai nevoie, se folosește rar dar totuși se folosește. Sunt cazuri când este folositor, doar ca trebuie folosit cu mare atenție.
    Se recomanda ca lock(this) sa fie folosit doar în metode private. O discuție interesanta pe aceasta tema am găsit aici: http://stackoverflow.com/questions/251391/why-is-lockthis-bad

    ReplyDelete
  2. Sustin ce spune Costin (Siderite). Nu e sanatos sa faci lock pe nimic ce ar putea fi vizibil din exterior. De aceea se recomanda sa se creeze un obiect (new object()) privat, readonly, minimalizand sansele de a obtine un deadlock. De asta nu e bine sa faci lock pe this, un string literal sau un System.Type.

    ReplyDelete
    Replies
    1. Iti dau 100% dreptate. Eu am pus accent pe atributul care poate sa fie adaugat pe metoda.
      Dar lock pe this nu e sanatos deloc.

      Delete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...