线程计时器
Threading.Timer 类对在单独线程中定期运行任务十分有用。例如,可以使用线程计时器检查数据库的状态和完整性,或者备份重要文件。以下示例每两秒钟启动一个任务,并使用标志来启动使计时器停止的 Dispose 方法。本例将状态发送到输出窗口,因此在测试代码之前,应按 CONTROL+ALT+O 键以使此窗口可见。
Class StateObjClass ' 用于保留调用 TimerTask 所需的参数 Public SomeValue As Integer Public TimerReference As System.Threading.Timer Public TimerCanceled As Boolean End Class Sub RunTimer() Dim StateObj As New StateObjClass() StateObj.TimerCanceled = False StateObj.SomeValue = 1 Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask) ' 创建每隔 2 秒钟调用过程的计时器。 ' 注意:这里没有 Start 方法;创建实例之后, ' 计时器就开始运行。 Dim TimerItem As New System.Threading.Timer(TimerDelegate, StateObj, _ 2000, 2000) StateObj.TimerReference = TimerItem ' 为 Dispose 保存一个引用。 While StateObj.SomeValue < 10 ' 运行 10 个循环。 System.Threading.Thread.Sleep(1000) ' 等待 1 秒钟。 End While StateObj.TimerCanceled = True ' 请求计时器对象的 Dispose。 End Sub Sub TimerTask(ByVal StateObj As Object) Dim State As StateObjClass = CType(StateObj, StateObjClass) Dim x As Integer ' 使用 Interlocked 类递增计数器变量。 System.Threading.Interlocked.Increment(State.SomeValue) Debug.WriteLine("已启动了新线程 " & Now) If State.TimerCanceled Then ' 已请求 Dispose。 State.TimerReference.Dispose() Debug.WriteLine("完成时间 " & Now) End If End Sub
当 System.Windows.Forms.Timer 类不可用时(例如在开发控制台应用程序时),线程计时器特别有用。
引文自:http://www.microsoft.com/china/MSDN/library/archives/library/dv_vstechart/html/vbtchasyncprocvb.asp