Synchronized methods in C#

c#, java, synchronized, thread-safety

Solution

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

Problem

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. In Java this can be solved using `synchronized` methods and `wait()` and `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#?

Original source

Related problems