Mutex Oluşturucular

Tanım

Mutex sınıfının yeni bir örneğini başlatır.

Aşırı Yüklemeler

Mutex()

Sınıfın Mutex yeni bir örneğini varsayılan özelliklerle başlatır.

Mutex(Boolean)

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini alıp almayacağını belirten bir Boole değeriyle başlatır.

Mutex(Boolean, String)

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini ve mutex'in adı olan bir dizeyi alıp almayacağını belirten boole değeriyle başlatır.

Mutex(Boolean, String, Boolean)

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini, mutex'in adı olan bir dizeyi ve yöntem döndürdüğünde çağıran iş parçacığına mutex'in ilk sahipliğini verilip verilmediğini gösteren boole değeriyle başlatır.

Mutex(Boolean, String, Boolean, MutexSecurity)

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini alıp almayacağını belirten boole değeriyle başlatır; mutex'in adı olan bir dize, yöntem döndürdüğünde çağıran iş parçacığına mutex'in ilk sahipliğini verilip verilmediğini ve adlandırılmış mutex'e uygulanacak erişim denetimi güvenliğini gösteren bir Boole değişkeni.

Mutex()

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Sınıfın Mutex yeni bir örneğini varsayılan özelliklerle başlatır.

public:
 Mutex();
public Mutex ();
Public Sub New ()

Örnekler

Aşağıdaki kod örneği, korumalı bir kaynağa erişimi eşitlemek için yerel Mutex bir nesnenin nasıl kullanıldığını gösterir. Mutex oluşturan iş parçacığı başlangıçta buna sahip değildir.

// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using namespace System;
using namespace System::Threading;
const int numIterations = 1;
const int numThreads = 3;
ref class Test
{
public:

   // Create a new Mutex. The creating thread does not own the
   // Mutex.
   static Mutex^ mut = gcnew Mutex;
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // The main thread exits, but the application continues to 
   // run until all foreground threads have exited.
}
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
 
using System;
using System.Threading;

class Test13
{
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.CurrentThread.Name);
         
        // Release the Mutex.
        mut.ReleaseMutex();
    }
}
' This example shows how a Mutex is used to synchronize access
' to a protected resource. Unlike Monitor, Mutex can be used with
' WaitHandle.WaitAll and WaitAny, and can be passed across
' AppDomain boundaries.
 
Imports System.Threading

Class Test
    ' Create a new Mutex. The creating thread does not own the
    ' Mutex.
    Private Shared mut As New Mutex()
    Private Const numIterations As Integer = 1
    Private Const numThreads As Integer = 3

    <MTAThread> _
    Shared Sub Main()
        ' Create the threads that will use the protected resource.
        Dim i As Integer
        For i = 1 To numThreads
            Dim myThread As New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)
            myThread.Start()
        Next i

        ' The main thread exits, but the application continues to
        ' run until all foreground threads have exited.

    End Sub

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 1 To numIterations
            UseResource()
        Next i
    End Sub

    ' This method represents a resource that must be synchronized
    ' so that only one thread at a time can enter.
    Private Shared Sub UseResource()
        ' Wait until it is safe to enter.
        mut.WaitOne()

        Console.WriteLine("{0} has entered protected area", _
            Thread.CurrentThread.Name)

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

        Console.WriteLine("{0} is leaving protected area" & vbCrLf, _
            Thread.CurrentThread.Name)

        ' Release Mutex.
        mut.ReleaseMutex()
    End Sub
End Class

Açıklamalar

Bu oluşturucu aşırı yüklemesini çağırmak, oluşturucu aşırı yüklemesini Mutex(Boolean) çağırmak ve mutex'in ilk sahipliğini belirtmekle false aynıdır. Yani çağıran iş parçacığı mutex'e sahip değildir.

Ayrıca bkz.

Şunlara uygulanır

Mutex(Boolean)

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini alıp almayacağını belirten bir Boole değeriyle başlatır.

public:
 Mutex(bool initiallyOwned);
public Mutex (bool initiallyOwned);
new System.Threading.Mutex : bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean)

Parametreler

initiallyOwned
Boolean

true çağıran iş parçacığına mutex'in ilk sahipliğini vermek için; aksi takdirde , false.

Örnekler

Aşağıdaki kod örneği, korumalı bir kaynağa erişimi eşitlemek için yerel Mutex bir nesnenin nasıl kullanıldığını gösterir. Oluşturan iş parçacığı başlangıçta bu iş parçacığının Mutex sahibidir.

using namespace System;
using namespace System::Threading;

const int numIterations = 1;
const int numThreads = 3;

ref class Test
{
public:

   // Create a new Mutex. The creating thread owns the
   // Mutex.
   static Mutex^ mut = gcnew Mutex( true );
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Initialize the Mutex.
   Mutex^ mut = Test::mut;
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // Wait one second before allowing other threads to
   // acquire the Mutex.
   Console::WriteLine( "Creating thread owns the Mutex." );
   Thread::Sleep( 1000 );
   Console::WriteLine( "Creating thread releases the Mutex.\r\n" );
   mut->ReleaseMutex();
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
using System;
using System.Threading;

class Test
{
    private static Mutex mut;
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create a new Mutex. The creating thread owns the Mutex.
        mut = new Mutex(true);
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // Wait one second before allowing other threads to
        // acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.");
        Thread.Sleep(1000);

        Console.WriteLine("Creating thread releases the Mutex.\r\n");
        mut.ReleaseMutex();
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.CurrentThread.Name);
         
        // Release the Mutex.
        mut.ReleaseMutex();
    }
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
Imports System.Threading

Class Test
    ' Create a new Mutex. The creating thread owns the
    ' Mutex.
    Private Shared mut As New Mutex(True)
    Private Const numIterations As Integer = 1
    Private Const numThreads As Integer = 3

    <MTAThread> _
    Shared Sub Main()
        ' Create the threads that will use the protected resource.
        Dim i As Integer
        For i = 1 To numThreads
            Dim myThread As New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)
            myThread.Start()
        Next i

        ' Wait one second before allowing other threads to
        ' acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.")
        Thread.Sleep(1000)

        Console.WriteLine("Creating thread releases the Mutex." & vbCrLf)
        mut.ReleaseMutex()
    End Sub

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 1 To numIterations
            UseResource()
        Next i
    End Sub

    ' This method represents a resource that must be synchronized
    ' so that only one thread at a time can enter.
    Private Shared Sub UseResource()
        ' Wait until it is safe to enter.
        mut.WaitOne()

        Console.WriteLine("{0} has entered protected area", _
            Thread.CurrentThread.Name)

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

        Console.WriteLine("{0} is leaving protected area" & vbCrLf, _
            Thread.CurrentThread.Name)

        ' Release Mutex.
        mut.ReleaseMutex()
    End Sub
End Class
' The example displays output like the following:
'       Creating thread owns the Mutex.
'       Creating thread releases the Mutex.
'       
'       Thread1 has entered the protected area
'       Thread1 is leaving the protected area
'       
'       Thread2 has entered the protected area
'       Thread2 is leaving the protected area
'       
'       Thread3 has entered the protected area
'       Thread3 is leaving the protected area

Ayrıca bkz.

Şunlara uygulanır

Mutex(Boolean, String)

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini ve mutex'in adı olan bir dizeyi alıp almayacağını belirten boole değeriyle başlatır.

public:
 Mutex(bool initiallyOwned, System::String ^ name);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name);
public Mutex (bool initiallyOwned, string? name);
public Mutex (bool initiallyOwned, string name);
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string -> System.Threading.Mutex
new System.Threading.Mutex : bool * string -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String)

Parametreler

initiallyOwned
Boolean

true bu çağrının bir sonucu olarak adlandırılmış sistem mutex'i oluşturulduysa adlandırılmış sistem mutex'in çağıran iş parçacığına ilk sahipliğini vermek için; aksi takdirde , false.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; aksi takdirde veya null boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca bir ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışlanmadan sonraki ad geçerli bir dosya adı olmalıdır.

Öznitelikler

Özel durumlar

Adlandırılmış mutex var ve erişim denetimi güvenliğine sahip, ancak kullanıcının yok FullControl.

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından konulabilecek bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

Örnekler

Aşağıdaki örnek, iki ayrı işlemde çalışan iş parçacıkları arasında sinyal vermek için adlandırılmış bir mutex'in nasıl kullanıldığını gösterir.

Bu programı iki veya daha fazla komut penceresiyle çalıştırın. Her işlem adlı mutex'i MyMutextemsil eden bir Mutex nesnesi oluşturur. Adlandırılmış mutex, yaşam süresi onu temsil eden nesnelerin yaşam süreleri Mutex ile sınırlanmış bir sistem nesnesidir. Adlandırılmış mutex, ilk işlem nesnesini oluşturduğunda Mutex oluşturulur; bu örnekte adlandırılmış mutex, programı çalıştıran ilk işleme aittir. Adlandırılmış mutex, onu temsil eden tüm Mutex nesneler serbest bırakıldığında yok edilir.

Bu örnekte kullanılan oluşturucu aşırı yüklemesi çağıran iş parçacığına adlandırılmış mutex'in ilk sahipliğinin verilip verilmediğini söyleyemez. İş parçacığının adlandırılmış mutex'i oluşturacağından emin olmadığınız sürece ilk sahipliği istemek için bu oluşturucuyu kullanmamalısınız.

using namespace System;
using namespace System::Threading;

int main()
{
   // Create the named mutex. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object, regardless of which process or thread
   // caused "MyMutex" to be created.
   Mutex^ m = gcnew Mutex( false,"MyMutex" );
   
   // Try to gain control of the named mutex. If the mutex is 
   // controlled by another thread, wait for it to be released.        
   Console::WriteLine(  "Waiting for the Mutex." );
   m->WaitOne();
   
   // Keep control of the mutex until the user presses
   // ENTER.
   Console::WriteLine( "This application owns the mutex. "
   "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   m->ReleaseMutex();
}
using System;
using System.Threading;

public class Test1
{
    public static void Main()
    {
        // Create the named mutex. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object, regardless of which process or thread
        // caused "MyMutex" to be created.
        Mutex m = new Mutex(false, "MyMutex");
        
        // Try to gain control of the named mutex. If the mutex is 
        // controlled by another thread, wait for it to be released.        
        Console.WriteLine("Waiting for the Mutex.");
        m.WaitOne();

        // Keep control of the mutex until the user presses
        // ENTER.
        Console.WriteLine("This application owns the mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        m.ReleaseMutex();
    }
}
Imports System.Threading

Public Class Test
   Public Shared Sub Main()
      ' Create the named mutex. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object, regardless of which process or thread
      ' caused "MyMutex" to be created.
      Dim m As New Mutex(False, "MyMutex")
      
      ' Try to gain control of the named mutex. If the mutex is 
      ' controlled by another thread, wait for it to be released.        
      Console.WriteLine("Waiting for the Mutex.")
      m.WaitOne()
      
      ' Keep control of the mutex until the user presses
      ' ENTER.
      Console.WriteLine("This application owns the mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      m.ReleaseMutex()
   End Sub 
End Class

Açıklamalar

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum, oturum açma oturumudur ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, tümü aynı oturumda çalıştırıldığı bir üst/alt ilişki ile işlemler arasında eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, mevcut eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

null değilse name ve initiallyOwned isetrue, yalnızca adlandırılmış sistem mutex'i bu çağrının sonucu olarak oluşturulduysa çağıran iş parçacığı mutex'e sahip olur. Adlandırılmış sistem mutex'in oluşturulup oluşturulmadığını belirlemek için bir mekanizma olmadığından, bu oluşturucu aşırı yüklemesini çağırırken öğesini initiallyOwned belirtmek false daha iyidir. İlk sahipliği belirlemeniz gerekiyorsa oluşturucuyu kullanabilirsiniz Mutex(Boolean, String, Boolean) .

Bu oluşturucu, adlandırılmış bir Mutex sistem mutex'ini temsil eden bir nesne başlatır. Aynı adlandırılmış sistem mutex'ini temsil eden birden çok Mutex nesne oluşturabilirsiniz.

Adlandırılmış mutex erişim denetimi güvenliğiyle önceden oluşturulduysa ve çağıranın yoksa MutexRights.FullControlbir özel durum oluşturulur. Mevcut adlandırılmış mutex'i yalnızca iş parçacığı etkinliklerini eşitlemek için gereken izinlerle açmak için yöntemine OpenExisting bakın.

için veya için nameboş bir dize belirtirseniznull, oluşturucuyu Mutex(Boolean) çağırmış gibi yerel bir mutex oluşturulur. Bu durumda, createdNew her zaman trueolur.

Bunlar sistem genelinde olduğundan, işlem sınırları arasında kaynak kullanımını koordine etmek için adlandırılmış mutex'ler kullanılabilir.

Not

Terminal Hizmetleri çalıştıran bir sunucuda, adlandırılmış bir sistem mutex'i iki görünürlük düzeyine sahip olabilir. Adı ön ekiyle Global\başlıyorsa, mutex tüm terminal sunucusu oturumlarında görünür. Adı ön ekiyle Local\başlıyorsa, mutex yalnızca oluşturulduğu terminal sunucusu oturumunda görünür. Bu durumda, sunucudaki diğer terminal sunucusu oturumlarının her birinde aynı ada sahip ayrı bir mutex bulunabilir. Adlandırılmış bir mutex oluştururken bir ön ek belirtmezseniz, ön ekini Local\alır. Terminal sunucusu oturumunda, adları yalnızca ön ekleriyle farklı olan iki mutex ayrı mutexes'tir ve her ikisi de terminal sunucusu oturumundaki tüm işlemler tarafından görülebilir. Diğer bir deyişle, ön ek adları Global\ ve Local\ işlemlere göre değil terminal sunucusu oturumlarına göre mutex adının kapsamını açıklar.

Dikkat

Varsayılan olarak, adlandırılmış bir mutex onu oluşturan kullanıcıyla sınırlı değildir. Diğer kullanıcılar mutex'i açabilir ve kullanabilir; örneğin, mutex'e girerek ve mutex'dan çıkmayarak müdahale edebilir. Unix benzeri işletim sistemlerinde, dosya sistemi adlandırılmış mutex'lerin uygulanmasında kullanılır ve diğer kullanıcılar adlandırılmış mutex'lere daha önemli yollarla müdahale edebilir. Windows'ta belirli kullanıcılara erişimi kısıtlamak için bir oluşturucu aşırı yüklemesi kullanabilir veya MutexAcl adlandırılmış mutex'i oluştururken bir MutexSecurity geçirebilirsiniz. Unix benzeri işletim sistemlerinde şu anda adlandırılmış bir mutex'e erişimi kısıtlamanın hiçbir yolu yoktur. Kod çalıştıran güvenilmeyen kullanıcıların bulunabileceği sistemlerde erişim kısıtlamaları olmadan adlandırılmış mutexes kullanmaktan kaçının.

Ters eğik çizgi (\), bir mutex adında ayrılmış bir karakterdir. Terminal sunucusu oturumlarında mutex'leri kullanma notunda belirtilenler dışında, bir mutex adında ters eğik çizgi (\) kullanmayın. Aksi takdirde, DirectoryNotFoundException mutex adı mevcut bir dosyayı temsil etse bile bir oluşturulabilir.

Ayrıca bkz.

Şunlara uygulanır

Mutex(Boolean, String, Boolean)

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini, mutex'in adı olan bir dizeyi ve yöntem döndürdüğünde çağıran iş parçacığına mutex'in ilk sahipliğini verilip verilmediğini gösteren boole değeriyle başlatır.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew);
public Mutex (bool initiallyOwned, string? name, out bool createdNew);
public Mutex (bool initiallyOwned, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string * bool -> System.Threading.Mutex
new System.Threading.Mutex : bool * string * bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, ByRef createdNew As Boolean)

Parametreler

initiallyOwned
Boolean

true bu çağrının bir sonucu olarak adlandırılmış sistem mutex'i oluşturulduysa adlandırılmış sistem mutex'in çağıran iş parçacığına ilk sahipliğini vermek için; aksi takdirde , false.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; aksi takdirde veya null boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca bir ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışlanmadan sonraki ad geçerli bir dosya adı olmalıdır.

createdNew
Boolean

Bu yöntem döndürdüğünde, yerel bir mutex (nullname varsa veya boş bir dize) oluşturulduysa veya belirtilen adlandırılmış sistem mutex'i oluşturulduysa; belirtilen adlandırılmış sistem mutex'i zaten mevcutsa bir false Boole true değeri içerir. Bu parametre, başlatmadan iletilir.

Öznitelikler

Özel durumlar

Adlandırılmış mutex var ve erişim denetimi güvenliğine sahip, ancak kullanıcının yok FullControl.

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından konulabilecek bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

Örnekler

Aşağıdaki kod örneği, adlandırılmış bir mutex'in işlemler veya iş parçacıkları arasında sinyal vermek için nasıl kullanıldığını gösterir. Bu programı iki veya daha fazla komut penceresiyle çalıştırın. Her işlem, "MyMutex" adlı mutex'i temsil eden bir Mutex nesne oluşturur. Adlandırılmış mutex bir sistem nesnesidir. Bu örnekte, yaşam süresi, onu temsil eden nesnelerin yaşam süreleri Mutex ile sınırlanır. adlandırılmış mutex, ilk işlem kendi yerel Mutex nesnesini oluşturduğunda oluşturulur ve onu temsil eden tüm Mutex nesneler serbest bırakıldığında yok edilir. Adlandırılmış mutex başlangıçta ilk işleme aittir. İkinci işlem ve sonraki işlemler, adlandırılmış mutex'i serbest bırakmak için önceki işlemleri bekler.

// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.
using namespace System;
using namespace System::Threading;
int main()
{
   
   // Set this variable to false if you do not want to request 
   // initial ownership of the named mutex.
   bool requestInitialOwnership = true;
   bool mutexWasCreated;
   
   // Request initial ownership of the named mutex by passing
   // true for the first parameter. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object. If "MyMutex" is created by this call,
   // then mutexWasCreated contains true; otherwise, it contains
   // false.
   Mutex^ m = gcnew Mutex( requestInitialOwnership, "MyMutex", mutexWasCreated );
   
   // This thread owns the mutex only if it both requested 
   // initial ownership and created the named mutex. Otherwise,
   // it can request the named mutex by calling WaitOne.
   if (  !(requestInitialOwnership && mutexWasCreated) )
   {
      Console::WriteLine(  "Waiting for the named mutex." );
      m->WaitOne();
   }

   
   // Once the process has gained control of the named mutex,
   // hold onto it until the user presses ENTER.
   Console::WriteLine(  "This process owns the named mutex. "
    "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   
   // Call ReleaseMutex to allow other threads to gain control
   // of the named mutex. If you keep a reference to the local
   // Mutex, you can call WaitOne to request control of the 
   // named mutex.
   m->ReleaseMutex();
}
// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.

using System;
using System.Threading;

public class Test12
{
    public static void Main()
    {
        // Set this variable to false if you do not want to request 
        // initial ownership of the named mutex.
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing
        // true for the first parameter. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);
        
        // This thread owns the mutex only if it both requested 
        // initial ownership and created the named mutex. Otherwise,
        // it can request the named mutex by calling WaitOne.
        if (!(requestInitialOwnership && mutexWasCreated))
        {
            Console.WriteLine("Waiting for the named mutex.");
            m.WaitOne();
        }

        // Once the process has gained control of the named mutex,
        // hold onto it until the user presses ENTER.
        Console.WriteLine("This process owns the named mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        // Call ReleaseMutex to allow other threads to gain control
        // of the named mutex. If you keep a reference to the local
        // Mutex, you can call WaitOne to request control of the 
        // named mutex.
        m.ReleaseMutex();
    }
}
' This example shows how a named mutex is used to signal between
' processes or threads.
' Run this program from two (or more) command windows. Each process
' creates a Mutex object that represents the named mutex "MyMutex".
' The named mutex is a system object whose lifetime is bounded by the
' lifetimes of the Mutex objects that represent it. The named mutex
' is created when the first process creates its local Mutex; in this
' example, the named mutex is owned by the first process. The named 
' mutex is destroyed when all the Mutex objects that represent it
' have been released. 
' The second process (and any subsequent process) waits for earlier
' processes to release the named mutex.

Imports System.Threading

Public Class Test
   
   <MTAThread> _
   Public Shared Sub Main()
      ' Set this variable to false if you do not want to request 
      ' initial ownership of the named mutex.
      Dim requestInitialOwnership As Boolean = True
      Dim mutexWasCreated As Boolean
      
      ' Request initial ownership of the named mutex by passing
      ' true for the first parameter. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object. If "MyMutex" is created by this call,
      ' then mutexWasCreated contains true; otherwise, it contains
      ' false.
      Dim m As New Mutex(requestInitialOwnership, "MyMutex", _
          mutexWasCreated)
      
      ' This thread owns the mutex only if it both requested 
      ' initial ownership and created the named mutex. Otherwise,
      ' it can request the named mutex by calling WaitOne.
      If Not (requestInitialOwnership And mutexWasCreated) Then
         Console.WriteLine("Waiting for the named mutex.")
         m.WaitOne()
      End If
      
      ' Once the process has gained control of the named mutex,
      ' hold onto it until the user presses ENTER.
      Console.WriteLine("This process owns the named mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      ' Call ReleaseMutex to allow other threads to gain control
      ' of the named mutex. If you keep a reference to the local
      ' Mutex, you can call WaitOne to request control of the 
      ' named mutex.
      m.ReleaseMutex()
   End Sub
End Class

Açıklamalar

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum, oturum açma oturumudur ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, tümü aynı oturumda çalıştırıldığı bir üst/alt ilişki ile işlemler arasında eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, mevcut eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

değilse name ve initiallyOwned isetrue, çağıran iş parçacığı adlandırılmış mutex'e yalnızca çağrıdan sonraysa createdNew sahip olurtrue.null Aksi takdirde iş parçacığı yöntemini çağırarak WaitOne mutex isteyebilir.

Bu oluşturucu, adlandırılmış bir Mutex sistem mutex'ini temsil eden bir nesne başlatır. Aynı adlandırılmış sistem mutex'ini temsil eden birden çok Mutex nesne oluşturabilirsiniz.

Adlandırılmış mutex erişim denetimi güvenliğiyle önceden oluşturulduysa ve çağıranın hakları yoksa MutexRights.FullControl , bir özel durum oluşturulur. Mevcut adlandırılmış mutex'i yalnızca iş parçacığı etkinliklerini eşitlemek için gereken izinlerle açmak için yöntemine OpenExisting bakın.

için veya için nameboş bir dize belirtirseniznull, oluşturucuyu Mutex(Boolean) çağırmış gibi yerel bir mutex oluşturulur. Bu durumda, createdNew her zaman trueolur.

Bunlar sistem genelinde olduğundan, işlem sınırları arasında kaynak kullanımını koordine etmek için adlandırılmış mutex'ler kullanılabilir.

Not

Terminal Hizmetleri çalıştıran bir sunucuda, adlandırılmış bir sistem mutex'i iki görünürlük düzeyine sahip olabilir. Adı ön ekiyle Global\başlıyorsa, mutex tüm terminal sunucusu oturumlarında görünür. Adı ön ekiyle Local\başlıyorsa, mutex yalnızca oluşturulduğu terminal sunucusu oturumunda görünür. Bu durumda, sunucudaki diğer terminal sunucusu oturumlarının her birinde aynı ada sahip ayrı bir mutex bulunabilir. Adlandırılmış bir mutex oluştururken bir ön ek belirtmezseniz, ön ekini Local\alır. Terminal sunucusu oturumunda, adları yalnızca ön ekleriyle farklı olan iki mutex ayrı mutexes'tir ve her ikisi de terminal sunucusu oturumundaki tüm işlemler tarafından görülebilir. Diğer bir deyişle, ön ek adları Global\ ve Local\ işlemlere göre değil terminal sunucusu oturumlarına göre mutex adının kapsamını açıklar.

Dikkat

Varsayılan olarak, adlandırılmış bir mutex onu oluşturan kullanıcıyla sınırlı değildir. Diğer kullanıcılar mutex'i açabilir ve kullanabilir; örneğin, mutex'e girerek ve mutex'dan çıkmayarak müdahale edebilir. Unix benzeri işletim sistemlerinde, dosya sistemi adlandırılmış mutex'lerin uygulanmasında kullanılır ve diğer kullanıcılar adlandırılmış mutex'lere daha önemli yollarla müdahale edebilir. Windows'ta belirli kullanıcılara erişimi kısıtlamak için bir oluşturucu aşırı yüklemesi kullanabilir veya MutexAcl adlandırılmış mutex'i oluştururken bir MutexSecurity geçirebilirsiniz. Unix benzeri işletim sistemlerinde şu anda adlandırılmış bir mutex'e erişimi kısıtlamanın hiçbir yolu yoktur. Kod çalıştıran güvenilmeyen kullanıcıların bulunabileceği sistemlerde erişim kısıtlamaları olmadan adlandırılmış mutexes kullanmaktan kaçının.

Ters eğik çizgi (\), bir mutex adında ayrılmış bir karakterdir. Terminal sunucusu oturumlarında mutex'leri kullanma notunda belirtilenler dışında, bir mutex adında ters eğik çizgi (\) kullanmayın. Aksi takdirde, DirectoryNotFoundException mutex adı mevcut bir dosyayı temsil etse bile bir oluşturulabilir.

Ayrıca bkz.

Şunlara uygulanır

Mutex(Boolean, String, Boolean, MutexSecurity)

Sınıfının yeni bir örneğini çağıran iş parçacığının Mutex mutex'in ilk sahipliğini, mutex'in adı olan bir dizeyi, yöntem döndürdüğünde çağıran iş parçacığına mutex'in ilk sahipliğini verilip verilmediğini ve adlandırılmış mutex'e uygulanacak erişim denetimi güvenliğini gösteren bir Boole değişkeniyle başlatır.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::MutexSecurity ^ mutexSecurity);
public Mutex (bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity);
new System.Threading.Mutex : bool * string * bool * System.Security.AccessControl.MutexSecurity -> System.Threading.Mutex
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string * bool * System.Security.AccessControl.MutexSecurity -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, ByRef createdNew As Boolean, mutexSecurity As MutexSecurity)

Parametreler

initiallyOwned
Boolean

true bu çağrının bir sonucu olarak adlandırılmış sistem mutex'i oluşturulduysa adlandırılmış sistem mutex'in çağıran iş parçacığına ilk sahipliğini vermek için; aksi takdirde , false.

name
String

Eşitleme nesnesi diğer işlemlerle paylaşılacaksa adı; aksi takdirde veya null boş bir dize. Bu ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca bir ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde ad alanı dışlanmadan sonraki ad geçerli bir dosya adı olmalıdır.

createdNew
Boolean

Bu yöntem döndürdüğünde, yerel bir mutex (nullname varsa veya boş bir dize) oluşturulduysa veya belirtilen adlandırılmış sistem mutex'i oluşturulduysa; belirtilen adlandırılmış sistem mutex'i zaten mevcutsa bir false Boole true değeri içerir. Bu parametre, başlatmadan iletilir.

mutexSecurity
MutexSecurity

MutexSecurity Adlandırılmış sistem mutex'ine uygulanacak erişim denetimi güvenliğini temsil eden nesne.

Öznitelikler

Özel durumlar

name geçersizdir. Bu, bilinmeyen bir ön ek veya geçersiz karakterler gibi işletim sistemi tarafından konulabilecek bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve ortak ön eklerin "Genel\" ve "Yerel\" büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. Özelliği HResult daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz . Nesne Adları .

name Çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış mutex var ve erişim denetimi güvenliğine sahip, ancak kullanıcının yok FullControl.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir.

Yalnızca .NET Framework: name MAX_PATH(260 karakter) uzundur.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliğine sahip adlandırılmış bir mutex'in işlemler arası davranışını gösterir. Örnek, adlandırılmış bir mutex'in varlığını test etmek için yöntem aşırı yüklemesini kullanır OpenExisting(String) .

Mutex yoksa, geçerli kullanıcıya mutex kullanma hakkını reddeden ancak mutex üzerinde okuma ve değiştirme izinleri veren ilk sahiplik ve erişim denetimi güvenliği ile oluşturulur.

Derlenmiş örneği iki komut penceresiyle çalıştırırsanız, ikinci kopya çağrısında OpenExisting(String)bir erişim ihlali özel durumu oluşturur. Özel durum yakalanır ve örnek, izinleri okumak ve değiştirmek için gereken haklarla mutex'i açmak için yöntem aşırı yüklemesini kullanır OpenExisting(String, MutexRights) .

İzinler değiştirildikten sonra, mutex girmek ve serbest bırakmak için gereken haklarla açılır. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinler kullanılarak çalıştırılır.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ mutexName = L"MutexExample4";

      Mutex^ m = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the mutex
      // constructor. It is true if the named system mutex was
      // created, and false if the named mutex already existed.
      //
      bool mutexWasCreated = false;

      // Attempt to open the named mutex.
      try
      {
         // Open the mutex with (MutexRights.Synchronize |
         // MutexRights.Modify), to enter and release the
         // named mutex.
         //
         m = Mutex::OpenExisting( mutexName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The mutex does not exist.
      // (2) The mutex exists, but the current user doesn't
      // have access. (3) The mutex exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The mutex does not exist, so create it.
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // mutex, but allows the right to read and change
         // security information for the mutex.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::ReadPermissions |
                MutexRights::ChangePermissions),
            AccessControlType::Allow );
         mSec->AddAccessRule( rule );
         
         // Create a Mutex object that represents the system
         // mutex named by the constant 'mutexName', with
         // initial ownership for this thread, and with the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in mutexWasCreated.
         //
         m = gcnew Mutex( true,mutexName, mutexWasCreated,mSec );
         
         // If the named system mutex was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the mutex. Otherwise, exit the program.
         //
         if ( mutexWasCreated )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the mutex." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the mutex to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            m = Mutex::OpenExisting( mutexName,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"Updated mutex security." );
            
            // Open the mutex with (MutexRights.Synchronize
            // | MutexRights.Modify), the rights required to
            // enter and release the mutex.
            //
            m = Mutex::OpenExisting( mutexName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine(
               L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // If this program created the mutex, it already owns
      // the mutex.
      //
      if ( !mutexWasCreated )
      {
         // Enter the mutex, and hold it until the program
         // exits.
         //
         try
         {
            Console::WriteLine( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the mutex
        // constructor. It is true if the named system mutex was
        // created, and false if the named mutex already existed.
        //
        bool mutexWasCreated = false;

        // Attempt to open the named mutex.
        try
        {
            // Open the mutex with (MutexRights.Synchronize |
            // MutexRights.Modify), to enter and release the
            // named mutex.
            //
            m = Mutex.OpenExisting(mutexName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Mutex does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The mutex does not exist.
        // (2) The mutex exists, but the current user doesn't 
        // have access. (3) The mutex exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The mutex does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // mutex, but allows the right to read and change
            // security information for the mutex.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            var mSec = new MutexSecurity();

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

                Console.WriteLine("Updated mutex security.");

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the mutex
        ' constructor. It is True if the named system mutex was
        ' created, and False if the named mutex already existed.
        '
        Dim mutexWasCreated As Boolean

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' mutex, but allows the right to read and change
            ' security information for the mutex.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim mSec As New MutexSecurity()

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

Açıklamalar

name bir ad alanı belirtmek için veya Local\ ön ekine Global\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows'da oturum bir oturum açma oturumudur ve hizmetler genellikle farklı bir etkileşimli olmayan oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, işlemlerin aynı oturumda çalıştırıldığı bir üst/alt ilişki ile eşitleme için uygun olabilir. Windows'da eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Nesne Adları.

bir name sağlanırsa ve istenen türdeki bir eşitleme nesnesi ad alanında zaten varsa, var olan eşitleme nesnesi kullanılır. Ad alanında farklı türde bir eşitleme nesnesi zaten varsa, bir WaitHandleCannotBeOpenedException oluşturulur. Aksi takdirde, yeni bir eşitleme nesnesi oluşturulur.

ve değilse, çağıran iş parçacığı adlandırılmış mutex'e yalnızca çağrıdan sonraysa createdNew sahip olurtrue.namenullinitiallyOwnedtrue Aksi takdirde iş parçacığı yöntemini çağırarak WaitOne mutex isteyebilir.

Bu oluşturucuyu, oluşturulduğunda adlandırılmış bir sistem mutex'ine erişim denetimi güvenliği uygulamak ve diğer kodun mutex denetimini almasını engellemek için kullanın.

Bu oluşturucu, adlandırılmış bir Mutex sistem mutex'ini temsil eden bir nesne başlatır. Aynı adlandırılmış sistem mutex'ini temsil eden birden çok Mutex nesne oluşturabilirsiniz.

Adlandırılmış sistem mutex'i yoksa, belirtilen erişim denetimi güvenliğiyle oluşturulur. Adlandırılmış mutex varsa, belirtilen erişim denetimi güvenliği yoksayılır.

Not

Çağıran, geçerli kullanıcıya bazı erişim hakları vermeyi reddetse veya veremediğinde mutexSecurity bile yeni oluşturulan Mutex nesne üzerinde tam denetime sahiptir. Ancak, geçerli kullanıcı bir oluşturucu veya OpenExisting yöntem kullanarak aynı adlandırılmış mutex'i temsil eden başka bir Mutex nesne almaya çalışırsa, Windows erişim denetimi güvenliği uygulanır.

Adlandırılmış mutex erişim denetimi güvenliğiyle zaten oluşturulduysa ve çağıranın yoksa MutexRights.FullControl, bir özel durum oluşturulur. Var olan adlandırılmış mutex'i yalnızca iş parçacığı etkinliklerini eşitlemek için gereken izinlerle açmak için yöntemine OpenExisting bakın.

için veya için nameboş bir dize belirtirseniznull, oluşturucuyu Mutex(Boolean) çağırmış gibi yerel bir mutex oluşturulur. Bu durumda, createdNew her zaman trueolur.

Bunlar sistem genelinde olduğundan, işlem sınırları arasında kaynak kullanımını koordine etmek için adlandırılmış mutex'ler kullanılabilir.

Not

Terminal Hizmetleri çalıştıran bir sunucuda, adlandırılmış bir sistem mutex'i iki görünürlük düzeyine sahip olabilir. Adı ön ekiyle Global\başlıyorsa, mutex tüm terminal sunucusu oturumlarında görünür. Adı ön ekiyle Local\başlıyorsa, mutex yalnızca oluşturulduğu terminal sunucusu oturumunda görünür. Bu durumda, sunucudaki diğer terminal sunucusu oturumlarının her birinde aynı ada sahip ayrı bir mutex bulunabilir. Adlandırılmış bir mutex oluştururken bir ön ek belirtmezseniz, ön ekini Local\alır. Terminal sunucusu oturumunda, adları yalnızca ön ekleriyle farklılık gösteren iki mutex ayrı mutex'lerdir ve her ikisi de terminal sunucusu oturumundaki tüm işlemlere görünür. Diğer bir deyişle, ön ek adları Global\ ve Local\ işlemlere göre değil terminal sunucusu oturumlarına göre mutex adının kapsamını açıklar.

Dikkat

Varsayılan olarak, adlandırılmış bir mutex onu oluşturan kullanıcıyla sınırlı değildir. Diğer kullanıcılar mutex'i açabilir ve kullanabilir, örneğin mutex'e girerek mutekse müdahale edebilir ve bu durumdan çıkamayabilirler. Belirli kullanıcılara erişimi kısıtlamak için, adlandırılmış mutex'i oluştururken bir MutexSecurity geçirebilirsiniz. Kod çalıştıran güvenilmeyen kullanıcılara sahip olabilecek sistemlerde erişim kısıtlamaları olmadan adlandırılmış mutex'leri kullanmaktan kaçının.

Ters eğik çizgi (\), bir mutex adında ayrılmış bir karakterdir. Terminal sunucusu oturumlarında mutex'leri kullanma konusunda notta belirtilenler dışında, bir mutex adında ters eğik çizgi (\) kullanmayın. Aksi takdirde, DirectoryNotFoundException mutex adı mevcut bir dosyayı temsil etse bile oluşturulabilir.

Şunlara uygulanır