java C#中的同步方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15027522/
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
Synchronized methods in C#
提问by Dimme
Part of porting a Java application to C# is to implement a synchronized message buffer in C#. By synchronized I mean that it should be safe for threads to write and read messages to and from it.
将 Java 应用程序移植到 C# 的一部分是在 C# 中实现同步消息缓冲区。同步我的意思是线程向它写入消息和从它读取消息应该是安全的。
In Java this can be solved using synchronized
methods and wait()
and notifyAll()
.
在 Java 中,这可以使用synchronized
方法和wait()
和和来解决notifyAll()
。
Example:
例子:
public class MessageBuffer {
// Shared resources up here
public MessageBuffer() {
// Initiating the shared resources
}
public synchronized void post(Object obj) {
// Do stuff
wait();
// Do more stuff
notifyAll();
// Do even more stuff
}
public synchronized Object fetch() {
// Do stuff
wait();
// Do more stuff
notifyAll();
// Do even more stuff and return the object
}
}
How can I achieve something similar in C#?
我怎样才能在 C# 中实现类似的东西?
采纳答案by Dave Doknjas
Try this:
试试这个:
using System.Runtime.CompilerServices;
using System.Threading;
public class MessageBuffer
{
// Shared resources up here
public MessageBuffer()
{
// Initiating the shared resources
}
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual void post(object obj)
{
// Do stuff
Monitor.Wait(this);
// Do more stuff
Monitor.PulseAll(this);
// Do even more stuff
}
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual object fetch()
{
// Do stuff
Monitor.Wait(this);
// Do more stuff
Monitor.PulseAll(this);
// Do even more stuff and return the object
}
}
回答by bash.d
In .NET you can use the lock
-statement like in
在 .NET 中,您可以使用lock
-statement 像
object oLock = new object();
lock(oLock){
//do your stuff here
}
What you are looking for are mutexes or events.
You can use the ManualResetEvent
-class and make a thread wait via
您正在寻找的是互斥锁或事件。您可以使用ManualResetEvent
-class 并使线程等待通过
ManualResetEvent mre = new ManualResetEvent(false);
...
mre.WaitOne();
The other thread eventually calls
另一个线程最终调用
mre.Set();
to signal the other thread that it can continue.
通知另一个线程它可以继续。
Look here.
看这里。