Semaphore.Release Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Завершает семафор.
Перегрузки
| Имя | Описание |
|---|---|
| Release() |
Завершает семафор и возвращает предыдущее число. |
| Release(Int32) |
Завершает семафор заданное количество раз и возвращает предыдущее число. |
Release()
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
Завершает семафор и возвращает предыдущее число.
public:
int Release();
public int Release();
member this.Release : unit -> int
Public Function Release () As Integer
Возвращаемое значение
Количество семафора перед вызовом Release метода.
Исключения
Число семафоров уже находится в максимальном значении.
Ошибка Win32 произошла с именованным семафором.
Текущий семафор представляет именованный системный семафор, но у пользователя нет Modify.
–или–
Текущий семафор представляет именованный системный семафор, но он не был открыт с Modifyпомощью.
Примеры
В следующем примере кода создается семафор с максимальным числом трех и начальным числом нуля. В примере начинаются пять потоков, которые блокируют ожидание семафора. Основной поток использует Release(Int32) перегрузку метода для увеличения числа семафора до максимального, что позволяет трем потокам входить в семафор. Каждый поток использует Thread.Sleep метод для ожидания одной секунды, для имитации работы, а затем вызывает Release() перегрузку метода, чтобы освободить семафор.
Каждый раз при выпуске семафора отображается предыдущее число семафоров. Сообщения консоли отслеживают использование семафора. Имитированный рабочий интервал немного увеличивается для каждого потока, чтобы упростить чтение выходных данных.
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());
}
}
Imports System.Threading
Public Class Example
' A semaphore that simulates a limited resource pool.
'
Private Shared _pool As Semaphore
' A padding interval to make the output more orderly.
Private Shared _padding As Integer
<MTAThread> _
Public Shared Sub 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(0, 3)
' Create and start five numbered threads.
'
For i As Integer = 1 To 5
Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
'Dim t As New Thread(AddressOf Worker)
' Start the thread, passing the number.
'
t.Start(i)
Next 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(3)
Console.WriteLine("Main thread exits.")
End Sub
Private Shared Sub Worker(ByVal num As Object)
' 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.
Dim padding As Integer = Interlocked.Add(_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())
End Sub
End Class
Комментарии
Потоки обычно используют WaitOne метод для ввода семафора, и обычно используют эту перегрузку метода для выхода.
SemaphoreFullException Если метод вызывает исключениеRelease, это не обязательно указывает на проблему с вызывающим потоком. Ошибка программирования в другом потоке, возможно, привела к тому, что поток выходит из семафора больше раз, чем он введен.
Если текущий Semaphore объект представляет именованный системный семафор, пользователь должен иметь SemaphoreRights.Modify права и семафор должен быть открыт с SemaphoreRights.Modify правами.
См. также раздел
Применяется к
Release(Int32)
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
- Исходный код:
- Semaphore.cs
Завершает семафор заданное количество раз и возвращает предыдущее число.
public:
int Release(int releaseCount);
public int Release(int releaseCount);
member this.Release : int -> int
Public Function Release (releaseCount As Integer) As Integer
Параметры
- releaseCount
- Int32
Количество раз выхода из семафора.
Возвращаемое значение
Количество семафора перед вызовом Release метода.
Исключения
releaseCount меньше 1.
Число семафоров уже находится в максимальном значении.
Ошибка Win32 произошла с именованным семафором.
Текущий семафор представляет именованный системный семафор, но у пользователя нет Modify прав.
–или–
Текущий семафор представляет именованный системный семафор, но он не был открыт с Modify правами.
Примеры
В следующем примере кода создается семафор с максимальным числом трех и начальным числом нуля. В примере начинаются пять потоков, которые блокируют ожидание семафора. Основной поток использует Release(Int32) перегрузку метода для увеличения числа семафора до максимального, что позволяет трем потокам входить в семафор. Каждый поток использует Thread.Sleep метод для ожидания одной секунды, для имитации работы, а затем вызывает Release() перегрузку метода, чтобы освободить семафор.
Каждый раз при выпуске семафора отображается предыдущее число семафоров. Сообщения консоли отслеживают использование семафора. Имитированный рабочий интервал немного увеличивается для каждого потока, чтобы упростить чтение выходных данных.
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());
}
}
Imports System.Threading
Public Class Example
' A semaphore that simulates a limited resource pool.
'
Private Shared _pool As Semaphore
' A padding interval to make the output more orderly.
Private Shared _padding As Integer
<MTAThread> _
Public Shared Sub 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(0, 3)
' Create and start five numbered threads.
'
For i As Integer = 1 To 5
Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
'Dim t As New Thread(AddressOf Worker)
' Start the thread, passing the number.
'
t.Start(i)
Next 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(3)
Console.WriteLine("Main thread exits.")
End Sub
Private Shared Sub Worker(ByVal num As Object)
' 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.
Dim padding As Integer = Interlocked.Add(_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())
End Sub
End Class
Комментарии
Если поток вошел в семафор несколько раз, эта перегрузка метода позволяет восстановить все количество семафоров с помощью одного вызова.
SemaphoreFullException Если метод вызывает исключениеRelease, это не обязательно указывает на проблему с вызывающим потоком. Ошибка программирования в другом потоке, возможно, привела к тому, что поток выходит из семафора больше раз, чем он введен.
Если текущий Semaphore объект представляет именованный системный семафор, пользователь должен иметь SemaphoreRights.Modify права и семафор должен быть открыт с SemaphoreRights.Modify правами.