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#?
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
Process Synchronization in C/C++ CC++Server Side ProgrammingProgramming. Process synchronization is the technique to overcome the problem of concurrent access to shared data which can result in data inconsistency.
Synchronization in C# is a mechanism that makes sure only one process or thread accesses the critical section of the program. All the other threads have to wait until the critical section is free before they can enter it.
In .NET you can use the lock
-statement like in
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 mre = new ManualResetEvent(false);
...
mre.WaitOne();
The other thread eventually calls
mre.Set();
to signal the other thread that it can continue.
Look here.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With