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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too