C#相当于java的wait和notify?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/209281/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:11:31  来源:igfitidea点击:

C# equivalent to java's wait and notify?

c#javamultithreading

提问by Omar Kooheji

I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify?

我知道您可以在 c# 中使用 lock 锁定一个对象,但是您可以放弃锁定并等待其他东西通知您它已更改,就像您在 java 中使用 wait 和 notify 一样吗?

It seems to me that synchronised and lock in java and c# respectively are synonomous.

在我看来,java 和 c# 中的 synchronized 和 lock 分别是同义词。

采纳答案by Jon Skeet

The equivalent functionality (including the normal locking) is in the Monitorclass.

等效的功能(包括普通锁定)在Monitor类中。

foo.notify() => Monitor.Pulse(foo)
foo.notifyAll() => Monitor.PulseAll(foo)
foo.wait() =>  Monitor.Wait(foo)

The lockstatement in C# is equivalent to calling Monitor.Enterand Monitor.Exitwith an appropriate try/finally block.

lockC# 中的语句等效于调用Monitor.EnterMonitor.Exit带有适当的 try/finally 块。

See my threading tutorialor Joe Albahari's onefor more details.

有关更多详细信息,请参阅我的线程教程Joe Albahari 的教程

回答by EBGreen

I think Wait Handles may work for you. See if thishelps.

我认为等待句柄可能适合你。看看这是否有帮助。