Synchronized Methods in C #

Part of porting a Java application to C # is to implement a synchronized message buffer in C #. By means of synchronization, I mean that for threads it should be safe to write and read messages on it.

In Java, this can be solved using the synchronized and wait() and notifyAll() methods.

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 like this in C #?

+6
source share
2 answers

Try the following:

 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 } } 
+4
source

In .NET you can use lock state as in

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

What you are looking for is mutexes or events. You can use the ManualResetEvent class and make the thread wait through

 ManualResetEvent mre = new ManualResetEvent(false); ... mre.WaitOne(); 

Otherwise, another thread calls

 mre.Set(); 

to signal another thread that it can continue.

Take a look here .

+6
source

All Articles