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

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

     編輯:關於C語言

SetTimeout 完整實作


private string strTimeoutMethod = null;
private Timer myTimer;

public void SetTimeout(int ms, string methodName) {
    if (bolUserInteractive == false) return;
    if (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 == false) return;
    if (methodName == null || methodName.Trim().Length == 0) return;
    if (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);
}

關鍵設計細節

  • 雙 Timer 交替使用,避免衝突
  • 方法名稱驗證:存在性檢查 + 大小寫不敏感
  • ExecuteSub 安全執行,不拋出例外
  • 參數檢查嚴謹,null/空字串直接返回
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved