7

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#で同様のことを達成するにはどうすればよいですか?

4

2 に答える 2

7

lock.NET では、次のように -statementを使用できます

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

探しているのはミューテックスまたはイベントです。-class を使用しManualResetEventて、スレッドを待機させることができます

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

他のスレッドは最終的に呼び出します

mre.Set();

続行できることを他のスレッドに通知します。

ここを見てください。

于 2013-02-22T15:33:49.717 に答える
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
    }
}
于 2013-02-22T15:32:53.833 に答える