30 Temmuz 2017 Pazar

Monitor Sınıfı

Giriş
lock ifadesi derleyici tarafından arkada Monitor kodune çevrilir.Elimizde şöyle bir kod olsun
private static readonly Object obj = new Object();

lock (obj)
{
  // thread unsafe code
}
C# 3.0'da derleyici şu kodu üretir.
var temp = obj;

Monitor.Enter(temp);

try
{
  // body
}
finally
{
  Monitor.Exit(temp);
}
C# 4.0'da derleyici şu kodu üretir.
bool lockWasTaken = false;
var temp = obj;
try
{
  Monitor.Enter(temp, ref lockWasTaken);
  // body
}
finally
{
  if (lockWasTaken)
  {
    Monitor.Exit(temp); 
  }
}
Enter metodu
Açıklaması şöyle
Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke  Enter more than once without it blocking; however, an equal number of  Exit calls must be invoked before other threads waiting on the object will unblock.
TryEnter metodu
Şöyle yaparız.
if (Monitor.TryEnter(lockObj)) {
   try {
      // The critical section.
   }
   finally {
      // Ensure that the lock is released.
      Monitor.Exit(lockObj);
   }
}
TryEnter metodu - ref bool ile
Şöyle yaparız.
bool lockAcquired;

try
{
    Monitor.TryEnter(lockObj, ref lockAcquired);

    if (lockAcquired)
    {
        DoSomething();
    }
}
finally
{
    if (lockAcquired)
    {
        Monitor.Exit(lockObj);
    }
}

Hiç yorum yok:

Yorum Gönder