VB.NET多線程實(shí)現(xiàn)線程計(jì)時(shí)器

字號(hào):

Threading.Timer類對(duì)在單獨(dú)線程中定期運(yùn)行任務(wù)十分有用。例如,可以使用線程計(jì)時(shí)器檢查數(shù)據(jù)庫的狀態(tài)和完整性,或者備份重要文件。以下示例每?jī)擅腌妴?dòng)一個(gè)任務(wù),并使用標(biāo)志來啟動(dòng)使計(jì)時(shí)器停止的Dispose方法。本例將狀態(tài)發(fā)送到輸出窗口,因此在測(cè)試代碼之前,加入收藏 應(yīng)按CONTROL+ALT+O鍵以使此窗口可見。
    ClassStateObjClass'用于保留調(diào)用TimerTask所需的參數(shù)
    PublicSomeValueAsInteger
    PublicTimerReferenceAsSystem.Threading.Timer
    PublicTimerCanceledAsBooleanEndClassSubRunTimer()
    DimStateObjAsNewStateObjClass()
    StateObj.TimerCanceled=False
    StateObj.SomeValue=1
    DimTimerDelegateAsNewThreading.TimerCallback(AddressOfTimerTask) '創(chuàng)建每隔2秒鐘調(diào)用過程的計(jì)時(shí)器。
    '注意:這里沒有Start方法;創(chuàng)建實(shí)例之后,  '計(jì)時(shí)器就開始運(yùn)行。
    DimTimerItemAsNewSystem.Threading.Timer(TimerDelegate,StateObj,_2000,2000)
    StateObj.TimerReference=TimerItem '為Dispose保存一個(gè)引用。
    WhileStateObj.SomeValue<10'運(yùn)行10個(gè)循環(huán)。
    System.Threading.Thread.Sleep(1000) '等待1秒鐘。
    EndWhile
    StateObj.TimerCanceled=True '請(qǐng)求計(jì)時(shí)器對(duì)象的Dispose。
    End
    SubSubTimerTask(ByValStateObjAsObject)
    DimStateAsStateObjClass=CType(StateObj,StateObjClass)
    DimxAsInteger '使用Interlocked類遞增計(jì)數(shù)器變量。
    System.Threading.Interlocked.Increment(State.SomeValue)
    Debug.WriteLine("已啟動(dòng)了新線程"&Now)
    IfState.TimerCanceledThen  '已請(qǐng)求Dispose。
    State.TimerReference.Dispose()
    Debug.WriteLine("完成時(shí)間"&Now)
    End
    IfEndSub
    當(dāng)System.Windows.Forms.Timer類不可用時(shí)(例如在開發(fā)控制臺(tái)應(yīng)用程序時(shí)),線程計(jì)時(shí)器特別有用。