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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…