线程计时器

线程计时器

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值