首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 發現之旅第十四講:VB.NET 腳本引擎(上)─ SetInterval/SetTimeout 定時與延時調用實作

     編輯:關於C語言

SetTimeout 延時調用


private string strTimeoutMethod = null;
private Timer myTimer;

public void SetTimeout(int ms, string methodName) {
    if (!bolUserInteractive || myEngine == null) return;
    if (myIntervalTimer != null) { myIntervalTimer.Stop(); strTimerIntervalMethod = null; }
    if (myTimer == null) { myTimer = new Timer(); myTimer.Tick += myTimer_Tick; }
    myTimer.Interval = ms;
    strTimeoutMethod = methodName;
    myTimer.Start();
}

public void ClearTimeout() {
    myTimer?.Stop();
    strTimeoutMethod = null;
}

private void myTimer_Tick(object sender, EventArgs e) {
    myTimer.Stop();
    if (myEngine != null && strTimeoutMethod != null) {
        string m = strTimeoutMethod.Trim(); strTimeoutMethod = null;
        if (myEngine.HasMethod(m)) myEngine.ExecuteSub(m);
    }
}

SetInterval 定時調用


private Timer myIntervalTimer;
private string strTimerIntervalMethod;

public void SetInterval(int ms, string methodName) {
    if (!bolUserInteractive) return;
    if (methodName == null || myEngine == null) return;
    if (myTimer != null) { myTimer.Stop(); strTimeoutMethod = null; }
    if (!myEngine.HasMethod(methodName.Trim())) return;
    strTimerIntervalMethod = methodName.Trim();
    if (myIntervalTimer == null) { myIntervalTimer = new Timer(); myIntervalTimer.Tick += myIntervalTimer_Tick; }
    myIntervalTimer.Interval = ms;
    myIntervalTimer.Start();
}

public void ClearInterval() {
    myIntervalTimer?.Stop();
    strTimerIntervalMethod = null;
}

private void myIntervalTimer_Tick(object sender, EventArgs e) {
    if (myIntervalTimer != null) strTimerIntervalMethod = strTimerIntervalMethod.Trim();
    if (string.IsNullOrEmpty(strTimerIntervalMethod) || myEngine == null || !myEngine.HasMethod(strTimerIntervalMethod)) {
        myIntervalTimer?.Stop(); return;
    }
    myEngine.ExecuteSub(strTimerIntervalMethod);
}

互斥關係

  • 啟動 SetTimeout 會停止 SetInterval
  • 啟動 SetInterval 會停止 SetTimeout
  • 確保同一時間只有一種排程機制運行
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved