Freigeben über


Mutex-Klasse

Ein primitiver Synchronisierungstyp, der auch für die prozessübergreifende Synchronisierung verwendet werden kann.

Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ComVisibleAttribute(True)> _
Public NotInheritable Class Mutex
    Inherits WaitHandle
'Usage
Dim instance As Mutex
[ComVisibleAttribute(true)] 
public sealed class Mutex : WaitHandle
[ComVisibleAttribute(true)] 
public ref class Mutex sealed : public WaitHandle
/** @attribute ComVisibleAttribute(true) */ 
public final class Mutex extends WaitHandle
ComVisibleAttribute(true) 
public final class Mutex extends WaitHandle

Hinweise

Hinweis

Das auf diese Klasse angewendete HostProtectionAttribute-Attribut besitzt den Resources-Eigenschaftenwert Synchronization | ExternalThreading. Das HostProtectionAttribute hat keine Auswirkungen auf Desktopanwendungen (die normalerweise durch Doppelklicken auf ein Symbol, Eingeben eines Befehls oder eines URL in einem Browser gestartet werden). Weitere Informationen finden Sie unter der HostProtectionAttribute-Klasse oder unter SQL Server-Programmierung und Hostschutzattribute.

Wenn zwei oder mehr Threads gleichzeitig auf eine gemeinsam genutzte Ressource zugreifen müssen, benötigt das System einen Synchronisierungsmechanismus, der sicherstellt, dass die Ressource von jeweils nur einem Thread verwendet wird. Mutex ist ein primitiver Synchronisierungstyp, der jeweils nur einem Thread exklusiven Zugriff auf die gemeinsam genutzte Ressource gewährt. Wenn ein Thread einen Mutex erhält, wird ein zweiter Thread, der diesen Mutex abruft, so lange angehalten, bis der erste Thread den Mutex freigibt.

Sie können mit der WaitHandle.WaitOne-Methode den Besitz eines Mutex anfordern. Der Thread, der einen Mutex besitzt, kann denselben Mutex in wiederholten Aufrufen von WaitOne anfordern, ohne dass seine Ausführung blockiert wird. Der Thread muss jedoch die ReleaseMutex-Methode ebenso oft aufrufen, um den Besitz des Mutex wieder aufzuheben. Die Mutex-Klasse erzwingt Threadidentität, sodass ein Mutex nur von dem Thread freigegeben werden kann, der ihn erhalten hat. Im Unterschied dazu erzwingt die Semaphore-Klasse keine Threadidentität.

Wenn ein Thread beendet wird, während er einen Mutex besitzt, wird der Mutex abgebrochen. Der Zustand des Mutex wird auf signalisiert festgelegt, und der nächste Thread in der Warteschlange übernimmt den Besitz. Wenn kein Besitzer des Mutex bestimmt werden kann, ist der Zustand des Mutex signalisiert. Ab Version 2.0 von .NET Framework wird eine AbandonedMutexException im nächsten Thread ausgelöst, der den Mutex erhält. Vor Version 2.0 von .NET Framework wurde keine Ausnahme ausgelöst.

Warnung

Ein abgebrochener Mutex gibt einen schwerwiegenden Fehler im Code an. Wenn ein Thread beendet wird, ohne dass der Mutex freigegeben wird, ist der Zustand der vom Mutex geschützten Datenstrukturen möglicherweise nicht konsistent. Der nächste Thread, der den Besitz des Mutex anfordert, kann diese Ausnahme verarbeiten und fortfahren, wenn die Integrität der Datenstrukturen bestätigt werden kann.

Es gibt zwei Arten von Mutexen: lokale Mutexe und benannte Systemmutexe. Wenn Sie ein Mutex-Objekt mit einem Konstruktor erstellen, der einen Namen akzeptiert, wird das Objekt einem Betriebssystemobjekt mit demselben Namen zugeordnet. Benannte Systemmutexe sind innerhalb des Betriebssystems sichtbar und können verwendet werden, um die Aktivitäten von Prozessen zu synchronisieren. Sie können mehrere Mutex-Objekte erstellen, die denselben benannten Systemmutex darstellen, und Sie können einen vorhandenen benannten Systemmutex mithilfe der OpenExisting-Methode öffnen.

Ein lokaler Mutex ist nur innerhalb des Prozesses vorhanden. Er kann von jedem Thread innerhalb des Prozesses verwendet werden, der über einen Verweis auf das lokale Mutex-Objekt verfügt. Jedes Mutex-Objekt ist ein separater lokaler Mutex.

Beispiel

' 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
Imports System.Threading
Imports Microsoft.VisualBasic

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 'Main

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

    ' 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 'UseResource
End Class 'MyMainClass
// 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 Test
{
    // 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.
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.

import System.*;
import System.Threading.*;
import System.Threading.Thread;

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

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

    // 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();
        }
    } //MyThreadProc

    // 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.get_CurrentThread().get_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.get_CurrentThread().get_Name());

        // Release the Mutex.
        mut.ReleaseMutex();
    } //UseResource
} //Test

Vererbungshierarchie

System.Object
   System.MarshalByRefObject
     System.Threading.WaitHandle
      System.Threading.Mutex

Threadsicherheit

Dieser Typ ist bezüglich Multithreadoperationen sicher.

Plattformen

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

Mutex-Member
System.Threading-Namespace
WaitHandle
Thread

Weitere Ressourcen

Verwaltetes Threading
Mutexe
Verwaltetes und nicht verwaltetes Threading