c# lock and listen to CancellationToken

后端 未结 2 1054
粉色の甜心
粉色の甜心 2021-02-20 02:51

I want to use lock or a similar synchronization to protect a critical section. At the same time I want to listen to a CancellationToken.

Right now I\'m using a mutex lik

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 03:29

    Take a look at the new .NET 4.0 Framework feature SemaphoreSlim Class. It provides SemaphoreSlim.Wait(CancellationToken) method.

    Blocks the current thread until it can enter the SemaphoreSlim, while observing a CancellationToken

    From some point of view using Semaphore in such simple case could be an overhead because initially it was designed to provide an access for multiple threads, but perhaps you might find it useful.

    EDIT: The code snippet

    CancellationToken token = new CancellationToken();            
    SemaphoreSlim semaphore = new SemaphoreSlim(1,1);
    bool tokenCanceled = false;
    
    try {
       try {
          // block section entrance for other threads
          semaphore.Wait(token);
       }
       catch (OperationCanceledException) {
          // The token was canceled and the semaphore was NOT entered...
          tokenCanceled = true;
       }
       // critical section code
       // ...
       if (token.IsCancellationRequested)
       {
           // ...
       }
    }
    finally { 
       if (!tokenCanceled)
          semaphore.Release();
    }
    

提交回复
热议问题