C#中的同步方法

Dim*_*mme 6 c# java synchronized thread-safety

将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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

bas*_*h.d 6

在.NET中,您可以lock像使用-statement一样使用

object oLock = new object();
lock(oLock){
  //do your stuff here
}
Run Code Online (Sandbox Code Playgroud)

您正在寻找的是互斥或事件.您可以使用ManualResetEvent-class并使线程等待

ManualResetEvent mre = new ManualResetEvent(false);
...
mre.WaitOne();
Run Code Online (Sandbox Code Playgroud)

另一个线程最终调用

mre.Set();
Run Code Online (Sandbox Code Playgroud)

发信号通知另一个线程它可以继续.

你看这里.


Dav*_*jas 3

尝试这个:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不喜欢使用 MethodImplOptions.Synchronized,因为它相当于为每个方法“锁定此”。而“lock this”被认为有点狡猾,因为它增加了死锁的可能性。 (3认同)