Tuesday, 26 March 2013

A CPU Friendly Infinite loop in C#

To run a infinite loop to do some process, we will be using While loop,System.Threading,System.Timer and so on.., each of this having its own pro's and con's and some of that will trash the CPU performance.

In this blog I am going to post the simple technique and that will utilize less CPU.To achieve this we have to use EventWaitHandle from System.Threading class.The following example will show the usage.

C# Console app Example :



private static void Main(string[] args)
{
EventWaitHandle waithandler = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());do
{
          eventWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
          Console.WriteLine("..........Entered........");
         
// ToDo: Something else if desired.
} while (true);
}


The above example will print the " Entered " word with every one second delay interval and infinitely.



If you want to do the same in Asynchronous way ,there are lot of ways to do and you can find one of the  method in the below example.


C# Console app Example(Asynchronously) :



//Declare a delegate for Async operation.

public delegate void AsyncMethodCaller();
class Program
{
private static void Main(string[] args)
{
           // Create the delegate.

            AsyncMethodCaller caller = new AsyncMethodCaller(Program.AsyncKeepAlive);
            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(null, null);}

private static void AsyncKeepAlive()

{
EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());

do
{
 eventWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
 Console.WriteLine("..........Entered........");
 // ToDo: Something else if desired.
 } while (true);

 }


}


Hope you enjoyed this post.
Thanks for Reading.Happy Coding!!

2 comments:

  1. Awesome, thanks for that.

    ReplyDelete
  2. Thanks for this. Works great.

    Note that in the synchronous example I had to change:

    eventWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

    to

    waithandler.WaitOne(TimeSpan.FromSeconds(1));

    ReplyDelete