The easiest way to run code at the moment is in .NET.

I am looking for something nice and simple. For instance:

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

      

In my cases, I want to test some thread code and something happens in the middle of another function call.

0


a source to share


3 answers


I would use System.Threading.Timer, which fires only once and starts right away.



System.Threading.Timer _timer = new Timer(ProcessTimer, null, 3000, Timeout.Infinite);

      

0


a source


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(); 
} 

      

Then you could do



RunAfter(3000, () => z = 5;);

      

+1


a source


You can also use WaitHandle to wait until a timeout occurs in background work.

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

      

0


a source







All Articles