Timer.Dispose Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Освобождает все ресурсы, используемые текущим экземпляром Timer.
Перегрузки
| Имя | Описание |
|---|---|
| Dispose() |
Освобождает все ресурсы, используемые текущим экземпляром Timer. |
| Dispose(WaitHandle) |
Освобождает все ресурсы, используемые текущим экземпляром Timer и сигналом, когда таймер был удален. |
Dispose()
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
Освобождает все ресурсы, используемые текущим экземпляром Timer.
public:
virtual void Dispose();
public void Dispose();
abstract member Dispose : unit -> unit
override this.Dispose : unit -> unit
Public Sub Dispose ()
Реализации
Примеры
В следующем примере кода показано, как освободить ресурсы, содержащиеся в объекте Timer.
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(10);
// Create a timer that invokes CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
DateTime.Now);
var stateTimer = new Timer(statusChecker.CheckStatus,
autoEvent, 1000, 250);
// When autoEvent signals, change the period to every half second.
autoEvent.WaitOne();
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period to .5 seconds.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne();
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
// The example displays output like the following:
// 11:59:54.202 Creating timer.
//
// 11:59:55.217 Checking status 1.
// 11:59:55.466 Checking status 2.
// 11:59:55.716 Checking status 3.
// 11:59:55.968 Checking status 4.
// 11:59:56.218 Checking status 5.
// 11:59:56.470 Checking status 6.
// 11:59:56.722 Checking status 7.
// 11:59:56.972 Checking status 8.
// 11:59:57.223 Checking status 9.
// 11:59:57.473 Checking status 10.
//
// Changing period to .5 seconds.
//
// 11:59:57.474 Checking status 1.
// 11:59:57.976 Checking status 2.
// 11:59:58.476 Checking status 3.
// 11:59:58.977 Checking status 4.
// 11:59:59.477 Checking status 5.
// 11:59:59.977 Checking status 6.
// 12:00:00.478 Checking status 7.
// 12:00:00.980 Checking status 8.
// 12:00:01.481 Checking status 9.
// 12:00:01.981 Checking status 10.
//
// Destroying timer.
Imports System.Threading
Public Module Example
Public Sub Main()
' Use an AutoResetEvent to signal the timeout threshold in the
' timer callback has been reached.
Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)
' Create a timer that invokes CheckStatus after one second,
' and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer." & vbCrLf,
DateTime.Now)
Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus,
autoEvent, 1000, 250)
' When autoEvent signals, change the period to every half second.
autoEvent.WaitOne()
stateTimer.Change(0, 500)
Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)
' When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne()
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")
End Sub
End Module
Public Class StatusChecker
Dim invokeCount, maxCount As Integer
Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub
' The timer callback method.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.",
DateTime.Now, invokeCount)
If invokeCount = maxCount Then
' Reset the counter and signal the waiting thread.
invokeCount = 0
autoEvent.Set()
End If
End Sub
End Class
' The example displays output like the following:
' 11:59:54.202 Creating timer.
'
' 11:59:55.217 Checking status 1.
' 11:59:55.466 Checking status 2.
' 11:59:55.716 Checking status 3.
' 11:59:55.968 Checking status 4.
' 11:59:56.218 Checking status 5.
' 11:59:56.470 Checking status 6.
' 11:59:56.722 Checking status 7.
' 11:59:56.972 Checking status 8.
' 11:59:57.223 Checking status 9.
' 11:59:57.473 Checking status 10.
'
' Changing period to .5 seconds.
'
' 11:59:57.474 Checking status 1.
' 11:59:57.976 Checking status 2.
' 11:59:58.476 Checking status 3.
' 11:59:58.977 Checking status 4.
' 11:59:59.477 Checking status 5.
' 11:59:59.977 Checking status 6.
' 12:00:00.478 Checking status 7.
' 12:00:00.980 Checking status 8.
' 12:00:01.481 Checking status 9.
' 12:00:01.981 Checking status 10.
'
' Destroying timer.
Комментарии
Вызов Dispose позволяет ресурсам, используемым Timer перераспределенными для других целей. Дополнительные сведения см. в Disposeразделе "Очистка неуправляемых ресурсов".
Note
Обратные вызовы могут возникать после Dispose() вызова перегрузки метода, так как обратные вызовы таймера для выполнения потоками пула потоков. Вы можете использовать перегрузку Dispose(WaitHandle) метода для ожидания завершения всех обратных вызовов.
См. также раздел
Применяется к
Dispose(WaitHandle)
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
- Исходный код:
- Timer.cs
Освобождает все ресурсы, используемые текущим экземпляром Timer и сигналом, когда таймер был удален.
public:
bool Dispose(System::Threading::WaitHandle ^ notifyObject);
public bool Dispose(System.Threading.WaitHandle notifyObject);
member this.Dispose : System.Threading.WaitHandle -> bool
Public Function Dispose (notifyObject As WaitHandle) As Boolean
Параметры
- notifyObject
- WaitHandle
Сигнал WaitHandle о том, когда Timer он был удален.
Возвращаемое значение
true Значение falseв противном случае .
Исключения
Параметр notifyObject имеет значение null.
Комментарии
Вызов Dispose позволяет ресурсам, используемым Timer перераспределенными для других целей. Дополнительные сведения см. в Disposeразделе "Очистка неуправляемых ресурсов".
После завершения этого метода он сигнализирует WaitHandle указанному параметру notifyObject . Используйте эту перегрузку Dispose метода, если вы хотите заблокировать, пока не убедитесь, что таймер был удален. Таймер не удаляется до завершения всех обратных вызовов в очереди.
Note
Если обратный вызов использует Change метод для задания dueTime параметра нулевой, состояние гонки может возникать при Dispose(WaitHandle) вызове перегрузки метода: если таймер очереди нового обратного вызова, прежде чем Dispose(WaitHandle) перегрузка метода обнаруживает, что обратные вызовы отсутствуют в очереди, продолжает блокироваться; Dispose(WaitHandle) в противном случае таймер удаляется во время очереди нового обратного вызова. ObjectDisposedException и вызывается при вызове нового обратного Change вызова метода.