gpt4 book ai didi

c# - C# 中的同步方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:23 26 4
gpt4 key购买 nike

将 Java 应用程序移植到 C# 的一部分是在 C# 中实现同步消息缓冲区。同步的意思是线程在其中写入和读取消息应该是安全的。

在 Java 中,这可以使用 synchronized 方法以及 wait()notifyAll() 来解决。

例子:

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
}
}

如何在 C# 中实现类似的功能?

最佳答案

在 .NET 中,您可以使用 lock 语句,如

object oLock = new object();
lock(oLock){
//do your stuff here
}

您正在寻找的是互斥量或事件。您可以使用 ManualResetEvent 类并通过

使线程等待
ManualResetEvent mre = new ManualResetEvent(false);
...
mre.WaitOne();

另一个线程最终调用

mre.Set();

向另一个线程发出它可以继续的信号。

here .

关于c# - C# 中的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027522/

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