C# 如何在不循环的情况下等待布尔值(使用任何类型的等待/信号量/事件/互斥锁等)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12412167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to wait for a boolean without looping (using any kind of wait / semaphore / event / mutex, etc)
提问by Ignacio Soler Garcia
I need to stop a thread until another thread sets a boolean value and I don't want to share between them an event.
我需要停止一个线程,直到另一个线程设置一个布尔值并且我不想在它们之间共享一个 event。
What I currently have is the following code using a Sleep (and that's the code I want to change):
我目前拥有的是以下使用 Sleep 的代码(这是我想要更改的代码):
while (!_engine.IsReadyToStop())
{
System.Threading.Thread.Sleep(Properties.Settings.Default.IntervalForCheckingEngine);
}
Any ideas?
有任何想法吗?
EDIT TO CLARIFY THINGS:
编辑以澄清事情:
There is an object called _engine of a class that I don't own. I cannot modify it, that's why I don't want to share an event between them. I need to wait until a method of that class returns true.
我不拥有一个名为 _engine 的类的对象。我无法修改它,这就是我不想在他们之间共享事件的原因。我需要等到该类的方法返回true。
采纳答案by MoonStom
SpinWait.SpinUntilis the right answer, regardless where you're gonna place this code. SpinUntil offers "a nice mix of spinning, yielding, and sleeping in between invocations".
SpinWait.SpinUntil是正确的答案,无论您将此代码放在哪里。SpinUntil 提供了“在调用之间很好地结合了旋转、屈服和休眠”。
回答by L.B
declare as
声明为
AutoResetEvent _ReadyToStop = new AutoResetEvent(false);
and use as
并用作
_ReadyToStop.WaitOne();
and
和
_ReadyToStop.Set();
For more info see the Synchronization Primitives in .Net
回答by Tigran
If you are using C# 4.0, you can use:
如果您正在使用C# 4.0,则可以使用:
Task t = Task.Factory.StartNew (() => SomeCall(..));
t.Wait();
By using Task.Waitmethod.
通过使用Task.Wait方法。
If you have more than one task run one after another, you can use Task.ContinueWith:
如果您有多个任务一个接一个地运行,您可以使用Task.ContinueWith:
Task t = Task.Factory.StartNew (() =>SomeCall(..)).
ContinueWith(ExecuteAfterThisTaskFinishes(...);
t.Wait();
回答by gm127
A condition variable is the synchronization primitive you can use for waiting on a condition.
条件变量是可用于等待条件的同步原语。
It does not natively exist in .NET. But the following linkprovides 100% managed code for a condition variable class implemented in terms of SemaphoreSlim, AutoResetEvent and Monitor classes. It allows thread to wait on a condition. And can wake up one or more threads when condition is satisfied. In addition, it supports timeouts and CancellationTokens.
它本身并不存在于 .NET 中。但是下面的链接为在 SemaphoreSlim、AutoResetEvent 和 Monitor 类方面实现的条件变量类提供了 100% 托管代码。它允许线程在某个条件下等待。并且在满足条件时可以唤醒一个或多个线程。此外,它还支持超时和 CancellationTokens。
To wait on a condition you write code similar to the following:
要等待某个条件,您可以编写类似于以下内容的代码:
object queueLock = new object();
ConditionVariable notEmptyCondition = new ConditionVariable();
T Take() {
lock(queueLock) {
while(queue.Count == 0) {
// wait for queue to be not empty
notEmptyCondition.Wait(queueLock);
}
T item = queue.Dequeue();
if(queue.Count < 100) {
// notify producer queue not full anymore
notFullCondition.Pulse();
}
return item;
}
}
Then in another thread you can wake up one or more threads waiting on condition.
然后在另一个线程中,您可以唤醒一个或多个等待条件的线程。
lock(queueLock) {
//..add item here
notEmptyCondition.Pulse(); // or PulseAll
}

