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

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 …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…