本文介绍了C#的锁,听的CancellationToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用锁或类似的同步,以保护关键的部分。同时,我要听的CancellationToken。

现在,我用这样的互斥体,但互斥体不具有相同的良好性能。我可以使用,而不是互斥的任何其他同步类(包括新的.NET 4.0)的?

  WaitHandle.WaitAny(新[] {CancelToken.WaitHandle,_mutex});
CancelToken.ThrowIfCancellationRequested();
 

解决方案

看看新的 .NET 4.0框架功能的的。它提供了SemaphoreSlim.Wait(CancellationToken)方法。

从某些角度来看使用旗语在这种简单的情况可能是负担,因为它最初的目的是要为多个线程访问,但也许你会发现它是有用的。

编辑:code段

 的CancellationToken令牌=新的CancellationToken();
SemaphoreSlim信号=新SemaphoreSlim(1,1);

尝试 {
   //其他线程块段入口
   semaphore.Wait(标记);

   //临界区code
   // ...
   如果(token.IsCancellationRequested)
   {
       // ...
   }
}
最后 {
   semaphore.Release();
}
 

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 like this, but mutex doesn't have as good performance. Can I use any of other synchronization classes (including the new .Net 4.0) instead of the mutex?

WaitHandle.WaitAny(new[] { CancelToken.WaitHandle, _mutex});
CancelToken.ThrowIfCancellationRequested();
解决方案

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

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

try {
   // block section entrance for other threads
   semaphore.Wait(token);

   // critical section code
   // ...
   if (token.IsCancellationRequested)
   {
       // ...
   }
}
finally { 
   semaphore.Release();
}

这篇关于C#的锁,听的CancellationToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 23:10