代码之家  ›  专栏  ›  技术社区  ›  BCS

在.NET中在给定时间触发代码的最简单方法

  •  0
  • BCS  · 技术社区  · 16 年前

    我在找一些简单又漂亮的东西。例如:

    RunAfter(3, delegate() { z = 5; }); // run after 3 seconds
    FnThatTakes5Seconds();
    

    在我的例子中,我想测试一些线程代码,并在另一个函数调用的中间发生一些事情。

    3 回复  |  直到 16 年前
        1
  •  0
  •   Mike_G    16 年前

    我将使用一个只触发一次并立即启动的System.Threading.Timer。

    System.Threading.Timer _timer = new Timer(ProcessTimer, null, 3000, Timeout.Infinite);
    
        2
  •  1
  •   Adam Robinson    16 年前
    public static void RunAfter(int millisecondTimeout, 
        System.Threading.ThreadStart method) 
    { 
        System.Threading.Thread t = new System.Threading.Thread(() => 
        { 
            System.Threading.Thread.Sleep(millisecondTimeout); 
    
            method(); 
        }); 
    
        t.Start(); 
    } 
    

    你可以那么做

    RunAfter(3000, () => z = 5;);
    
        3
  •  0
  •   Karol Deland    16 年前

    您还可以使用waithandle来等待,直到backgroundworker中发生超时。

    ManualResetEvent objResetEvent = new ManualResetEvent();
    objResetEvent.WaitOne(timeout, ...);