gpt4 book ai didi

c# 锁定并监听 CancellationToken

转载 作者:太空狗 更新时间:2023-10-29 18:19:06 24 4
gpt4 key购买 nike

我想使用锁或类似的同步来保护临界区。同时我想听一个CancellationToken。

现在我正在使用这样的互斥锁,但互斥锁的性能不佳。我可以使用任何其他同步类(包括新的 .Net 4.0)来代替互斥量吗?

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

最佳答案

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

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

从某种角度来看,在这种简单的情况下使用信号量可能是一种开销,因为最初它被设计为为多线程提供访问,但也许您会发现它很有用。

编辑:代码片段

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

关于c# 锁定并监听 CancellationToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com