Op Englesch liesen Editéieren

Deelen iwwer


Semaphore Constructors

Definition

Initializes a new instance of the Semaphore class.

Overloads

Semaphore(Int32, Int32)

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

Semaphore(Int32, Int32, String)

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

Semaphore(Int32, Int32, String, Boolean)

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

Semaphore(Int32, Int32)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

C#
public Semaphore(int initialCount, int maximumCount);

Parameters

initialCount
Int32

The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32

The maximum number of requests for the semaphore that can be granted concurrently.

Exceptions

initialCount is greater than maximumCount.

maximumCount is less than 1.

-or-

initialCount is less than 0.

Examples

The following example creates a semaphore with a maximum count of three and an initial count of zero. The example starts five threads, which block waiting for the semaphore. The main thread uses the Release(Int32) method overload to increase the semaphore count to its maximum, allowing three threads to enter the semaphore. Each thread uses the Thread.Sleep method to wait for one second, to simulate work, and then calls the Release() method overload to release the semaphore. Each time the semaphore is released, the previous semaphore count is displayed. Console messages track semaphore use. The simulated work interval is increased slightly for each thread, to make the output easier to read.

C#
using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(initialCount: 0, maximumCount: 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(releaseCount: 3);

        Console.WriteLine("Main thread exits.");
    }

    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}

Remarks

This constructor initializes an unnamed semaphore. All threads that use an instance of such a semaphore must have references to the instance.

If initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. If you do not want to reserve any entries for the thread that creates the semaphore, use the same number for maximumCount and initialCount.

See also

Applies to

.NET 10 an aner Versiounen
Produkt Versiounen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Semaphore(Int32, Int32, String)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

C#
public Semaphore(int initialCount, int maximumCount, string name);
C#
public Semaphore(int initialCount, int maximumCount, string? name);

Parameters

initialCount
Int32

The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32

The maximum number of requests for the semaphore that can be granted concurrently.

name
String

The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. The name is case-sensitive. The backslash character (\) is reserved and may only be used to specify a namespace. For more information on namespaces, see the remarks section. There may be further restrictions on the name depending on the operating system. For example, on Unix-based operating systems, the name after excluding the namespace must be a valid file name.

Exceptions

initialCount is greater than maximumCount.

-or-

.NET Framework only: name is longer than MAX_PATH (260 characters).

maximumCount is less than 1.

-or-

initialCount is less than 0.

name is invalid. This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Note that the name and common prefixes "Global\" and "Local\" are case-sensitive.

-or-

There was some other error. The HResult property may provide more information.

Windows only: name specified an unknown namespace. See Object Names for more information.

The name is too long. Length restrictions may depend on the operating system or configuration.

The named semaphore exists and has access control security, and the user does not have FullControl.

A synchronization object with the provided name cannot be created. A synchronization object of a different type might have the same name.

Examples

The following code example demonstrates the cross-process behavior of a named semaphore. The example creates a named semaphore with a maximum count of five and an initial count of five. The program makes three calls to the WaitOne method. Thus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. Release one or more entries in the first copy of the program to unblock the second.

C#
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");

        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    }
}

Remarks

This constructor initializes a Semaphore object that represents a named system semaphore. You can create multiple Semaphore objects that represent the same named system semaphore.

The name may be prefixed with Global\ or Local\ to specify a namespace. When the Global namespace is specified, the synchronization object may be shared with any processes on the system. When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. On Windows, a session is a login session, and services typically run in a different non-interactive session. On Unix-like operating systems, each shell has its own session. Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. For more information about synchronization object names on Windows, see Object Names.

If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Otherwise, a new synchronization object is created.

If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. If you need to determine whether or not a named system semaphore was created, use the Semaphore(Int32, Int32, String, Boolean) constructor overload instead.

Wichteg

When you use this constructor overload, the recommended practice is to specify the same number for initialCount and maximumCount. If initialCount is less than maximumCount, and a named system semaphore is created, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. However, with this constructor overload there is no way to determine whether a named system semaphore was created.

If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload.

Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

If you want to find out whether a named system semaphore exists, use the OpenExisting method. The OpenExisting method attempts to open an existing named semaphore, and throws an exception if the system semaphore does not exist.

Warnung

By default, a named semaphore is not restricted to the user that created it. Other users may be able to open and use the semaphore, including interfering with the semaphore by acquiring the semaphore multiple times and not releasing it. To restrict access to specific users, you can use a constructor overload or SemaphoreAcl and pass in a SemaphoreSecurity when creating the named semaphore. Avoid using named semaphores without access restrictions on systems that might have untrusted users running code.

See also

Applies to

.NET 10 an aner Versiounen
Produkt Versiounen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Semaphore(Int32, Int32, String, Boolean)

Source:
Semaphore.cs
Source:
Semaphore.cs
Source:
Semaphore.cs

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

C#
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew);
C#
public Semaphore(int initialCount, int maximumCount, string? name, out bool createdNew);

Parameters

initialCount
Int32

The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32

The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String

The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. The name is case-sensitive. The backslash character (\) is reserved and may only be used to specify a namespace. For more information on namespaces, see the remarks section. There may be further restrictions on the name depending on the operating system. For example, on Unix-based operating systems, the name after excluding the namespace must be a valid file name.

createdNew
Boolean

When this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. This parameter is passed uninitialized.

Exceptions

initialCount is greater than maximumCount.

-or-

.NET Framework only: name is longer than MAX_PATH (260 characters).

maximumCount is less than 1.

-or-

initialCount is less than 0.

name is invalid. This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Note that the name and common prefixes "Global\" and "Local\" are case-sensitive.

-or-

There was some other error. The HResult property may provide more information.

Windows only: name specified an unknown namespace. See Object Names for more information.

The name is too long. Length restrictions may depend on the operating system or configuration.

The named semaphore exists and has access control security, and the user does not have FullControl.

A synchronization object with the provided name cannot be created. A synchronization object of a different type might have the same name.

Examples

The following code example demonstrates the cross-process behavior of a named semaphore. The example creates a named semaphore with a maximum count of five and an initial count of two. That is, it reserves three entries for the thread that calls the constructor. If createNew is false, the program makes three calls to the WaitOne method. Thus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. Release one or more entries in the first copy of the program to unblock the second.

C#
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // The value of this variable is set by the semaphore
        // constructor. It is true if the named system semaphore was
        // created, and false if the named semaphore already existed.
        //
        bool semaphoreWasCreated;

        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", 
            out semaphoreWasCreated);

        if (semaphoreWasCreated)
        {
            // If the named system semaphore was created, its count is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else
        {      
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } 
}

Remarks

The name may be prefixed with Global\ or Local\ to specify a namespace. When the Global namespace is specified, the synchronization object may be shared with any processes on the system. When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. On Windows, a session is a login session, and services typically run in a different non-interactive session. On Unix-like operating systems, each shell has its own session. Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. For more information about synchronization object names on Windows, see Object Names.

If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Otherwise, a new synchronization object is created.

This constructor initializes a Semaphore object that represents a named system semaphore. You can create multiple Semaphore objects that represent the same named system semaphore.

If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. Use createdNew to determine whether the system semaphore was created.

If initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. In this case, createdNew is always true.

Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

Warnung

By default, a named semaphore is not restricted to the user that created it. Other users may be able to open and use the semaphore, including interfering with the semaphore by acquiring the semaphore multiple times and not releasing it. To restrict access to specific users, you can use a constructor overload or SemaphoreAcl and pass in a SemaphoreSecurity when creating the named semaphore. Avoid using named semaphores without access restrictions on systems that might have untrusted users running code.

See also

Applies to

.NET 10 an aner Versiounen
Produkt Versiounen
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

C#
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew, System.Security.AccessControl.SemaphoreSecurity semaphoreSecurity);

Parameters

initialCount
Int32

The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32

The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String

The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. The name is case-sensitive. The backslash character (\) is reserved and may only be used to specify a namespace. For more information on namespaces, see the remarks section. There may be further restrictions on the name depending on the operating system. For example, on Unix-based operating systems, the name after excluding the namespace must be a valid file name.

createdNew
Boolean

When this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. This parameter is passed uninitialized.

semaphoreSecurity
SemaphoreSecurity

A SemaphoreSecurity object that represents the access control security to be applied to the named system semaphore.

Exceptions

initialCount is greater than maximumCount.

-or-

.NET Framework only: name is longer than MAX_PATH (260 characters).

maximumCount is less than 1.

-or-

initialCount is less than 0.

The named semaphore exists and has access control security, and the user does not have FullControl.

name is invalid. This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Note that the name and common prefixes "Global\" and "Local\" are case-sensitive.

-or-

There was some other error. The HResult property may provide more information.

Windows only: name specified an unknown namespace. See Object Names for more information.

The name is too long. Length restrictions may depend on the operating system or configuration.

A synchronization object with the provided name cannot be created. A synchronization object of a different type might have the same name.

Examples

The following code example demonstrates the cross-process behavior of a named semaphore with access control security. The example uses the OpenExisting(String) method overload to test for the existence of a named semaphore. If the semaphore does not exist, it is created with a maximum count of two and with access control security that denies the current user the right to use the semaphore but grants the right to read and change permissions on the semaphore. If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to the OpenExisting(String) method. The exception is caught, and the example uses the OpenExisting(String, SemaphoreRights) method overload to open the semaphore with the rights needed to read and change the permissions.

After the permissions are changed, the semaphore is opened with the rights required to enter and release. If you run the compiled example from a third command window, it runs using the new permissions.

C#
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

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

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

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

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

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

                // Open the semaphore with (SemaphoreRights.Synchronize 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}

Remarks

Use this constructor to apply access control security to a named system semaphore when it is created, preventing other code from taking control of the semaphore.

The name may be prefixed with Global\ or Local\ to specify a namespace. When the Global namespace is specified, the synchronization object may be shared with any processes on the system. When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. On Windows, a session is a login session, and services typically run in a different non-interactive session. On Unix-like operating systems, each shell has its own session. Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. For more information about synchronization object names on Windows, see Object Names.

If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Otherwise, a new synchronization object is created.

This constructor initializes a Semaphore object that represents a named system semaphore. You can create multiple Semaphore objects that represent the same named system semaphore.

If the named system semaphore does not exist, it is created with the specified access control security. If the named semaphore exists, the specified access control security is ignored.

Notiz

The caller has full control over the newly created Semaphore object even if semaphoreSecurity denies or fails to grant some access rights to the current user. However, if the current user attempts to get another Semaphore object to represent the same named semaphore, using either a constructor or the OpenExisting method, Windows access control security is applied.

If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. Use the createdNew parameter to determine whether the system semaphore was created by this constructor.

If initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. In this case, createdNew is always true.

Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

Warnung

By default, a named semaphore is not restricted to the user that created it. Other users may be able to open and use the semaphore, including interfering with the semaphore by acquiring the semaphore multiple times and not releasing it. To restrict access to specific users, you can pass in a SemaphoreSecurity when creating the named semaphore. Avoid using named semaphores without access restrictions on systems that might have untrusted users running code.

See also

Applies to

.NET Framework 4.8.1 an aner Versiounen
Produkt Versiounen
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1