Skip to main content

Use lock in a block that contains a call to an async method (await keyword)

Citeam urmatorul post, in care se explica o modalitate de a face lock in cazul in care in block-ul de lock contine un apel la o metoda async.
Pe scurt, pentru a evita ca doua sau mai multe thread-uri sa scrie simultan in acelasi fisier, se incerca sa se faca lock. Dar .NET 4.5 nu ne lasa sa avem urmatorul cod (si foarte bine face):
lock( this )
    var f = await storageFile.OpenAsync();
    await file.WriteAsync("some content");
Eroarea pe care o primim arata in felul urmator:
The 'await' operator cannot be used in the body of a lock statement.
In link-ul pe care l-am dat mai sus, s-a incercat implementarea unei solutii custom care face lock la o anumita portiune de cod. O alta varianta ar putea sa fie sa incerca sa folosim Task.Run. Cea ce am obtine ar fi ceva asemanator cu urmatorul cod
lock( this )
    var f = await storageFile.OpenAsync();
    Task.Run(async () => {await f.WriteAsync("some content") }).Wait();
Codul s-ar compila fara nici o problema dar la rulare am vedea ca aplicatia nu mai raspunde cand ajunge pe linia de cod care contine Task.Run. Din aceasta cauza se poate ajunge sa implementam ceva asemanator cu link-ul dat la inceputul postului.
Cea ce nu imi place la nici o solutie este ca combinatia dintre lock si async nu suna foarte bine. De ce ai vrea sa faci un lock si sa te asiguri ca doar un singur apel asyncron se executa. De foarte multe ori problema poate sa fie de design. Nu degeaba .NET nu iti permite aceasta funcționalitate.
Un await in interiorul unui lock poate sa genereze foarte usor un deadlock. Problema este destul de asemanatoare cu deadlock-ul care se obtinea cand apelam Monitor.Exit in interiorul unui ExisDisposable.Dispose.
Cand se face resume la cod in general ajungem pe acelasi thread, dar acest lucru nu e obligatoriu, din aceasta cauza putem sa ajungem pe un alt thread, care ar face unlock la un lock facut pe un alt thread.
Be aware, cand folositi await, nimeni nu va garanteaza ca la resume o sa ajungeti pe acelasi thread. Trebuie sa mai tinem cont de inca un lucru, o metoda la care facem await nu stim cat o dureze, iar un lock ar trebui sa fie facut pentru o perioada cat mai mica de timp. Pentru acest lucru putem sa facem lock pe codul pe care il executam inainte si dupa apelul la metoda await.
Codul pe care l-am obtine ar avea urmatoare forma:
var f = await storageFile.OpenAsync();
await f.WriteAsync("some content");
Da stiu, se doreste ca metoda WriteAsync sa fie executa intr-un lock. Dar acest lucru nu e sanatos. Daca vrem doar noi sa avem drept de scriere, atunci trebuie sa deschide fisierul in asa fel incat doar dintr-un singur loc sa se poata scrie. Pentru a putea face acest lucru este nevoie sa specificam ca parametru la metoda OpenAsync FileAccessMode.
var f = await storageFile.OpenAsync(File.AccessMode.ReadWriteNoCopyOnWrite);
sau (in functie de caz)
var f = await storageFile.OpenAsync(File.AccessMode.ReadWrite);
In concluzie, cand ajungeti la un caz cand aveti nevoie de a face lock pe un block de cod care contine apeluri de metode asincrone, ar fi bine sa faceti un review la cod si sa vedeti daca chiar aveti nevoie de asa ceva si daca nu este o greseala in design-ul aplicatiei.


  1. De curind am avut de a face cu programare multithread si sincronizare si am aflat ca "lock" e depasit in .Net. ReaderWriterLockSlim este mult mai corect ca functionalitate si in plus permite diferentierea intre read lock si write lock, adica poti avea mai multi readeri la un singur writer.


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 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)

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

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…