2013-07-23 2 views
10

Vengo dal mondo C++ quindi sono molto abituato a bloccare i thread e la protezione mutex. Supponendo che questa funzione di base:C# async/await - Limita numero di chiamate a metodi asincroni/blocco

async Task BasicProcess() { 
    // await time consuming task 
} 

Come posso bloccare questa funzione in modo che solo una BasicProcess possibile eseguire in una sola volta?

Questo è ciò che voglio raggiungere:

async Task BasicProcess() { 
    lock (BasicProcessLock) { 
     // await time consuming task 
    } 
} 
+5

Vedi http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988 .aspx per un'implementazione AsyncLock. –

risposta

29

È possibile utilizzare SemaphoreSlim (1) Per questo, un SemaphoreSlim creata con (1) farà in modo solo un thread può ottenere il blocco, altri thread che cercano di ottenere il lucchetto - attenderanno fino a colui che l'ha preso - rilascialo.
creare un membro privato:

private SemaphoreSlim _syncLock = new SemaphoreSlim(1); 

Poi nel codice do:

async Task BasicProcess() { 

    await _syncLock.WaitAsync(); //Only 1 thread can access the function or functions that use this lock, others trying to access - will wait until the first one released. 
    //Do your stuff.. 
    _syncLock.Release(); 

} 
+2

Tranne che questo ora bloccherà il thread chiamante, che non è l'ideale, se in realtà è pensato per essere asincrono. –

+0

Uso migliore "attendi _syncLock.WaitAsync();" - altrimenti, il thread verrà bloccato e l'attività non verrà eseguita. – jlahd

+0

Jon/jlahd - Grazie per questo, aggiornato per non bloccare. – ilansch

Problemi correlati