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. Nu stiam chestia asta. Chiar dragut. O mica observatie, insa: rareori se foloseste lock(this) pentru ca blocheaza tot obiectul, si in consecinta MethodImpl are aceeasi hiba.

    ReplyDelete
  2. 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
  3. 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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP