C# · 12月 26, 2021

C#中的同步方法

将 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#中实现类似的功能?

解决方法 试试这个: 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 }}