Last active
December 8, 2015 20:24
-
-
Save Phyyl/e5357a7f42263a13a4b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LockSimple // Un seul access, pas de async/await | |
{ | |
private readonly object lockObj = new object(); | |
public void DoStuff() | |
{ | |
// Si ya personne qui a lock "lockObj", on rentre et on lock. | |
// On unlock a la fin du block "lock (lockObj) {}" | |
lock (lockObj) | |
{ | |
// Do stuff on your own | |
} | |
} | |
} | |
class LockMulti // Multi lock, async/await possible | |
{ | |
// Premier param = combien d'acces sont disponibles au depart | |
// Deuxieme param = combien d'acces max on peut avoir | |
// Si tu veux juste un acces, tu mets (1, 1) pour avoir 1 de dispo, et 1 max | |
private readonly SemaphoreSlim lockObj = new SemaphoreSlim(1, 1); | |
public void DoStuff() | |
{ | |
DoStuffAsync().Wait(); // On fait la meme chose que dans "DoStuffAsync", mais au lieu de faire autre chose, on attend d'avoir fini pour continuer (.Wait()) | |
} | |
public async Task DoStuffAsync() | |
{ | |
try | |
{ | |
await lockObj.WaitAsync(); // On bloque ici en "async", on resume quand on a acces | |
//Do stuff | |
} | |
finally // On s'assure que peut importe ce qui se passe dans le try, on va release le lock! (pour pas d'interbloquage) | |
{ | |
lockObj.Release(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment