Usage criteria for IAsyncResult.IsCompleted, iftAR.AsyncWaitHandle.WaitOne and AsyncCallback

I am learning the async concept of delegates and here I am confused on the difference between using the IAsyncResult.IsCompleted, iftAR.AsyncWaitHandle.WaitOne and AsyncCallback (in which you define new function with IAsyncResult as parameter).

I’m confused because suppose you use while loop to check for above 3 values, then in each of the 3 cases, you are checking in while loop whether the particular operation has completed executing. Then, what is the difference between the 3?

CASE 1 Code:

    static void Main(string[] args)
    {
     Console.WriteLine("***** Async Delegate Invocation *****");
      // Print out the ID of the executing thread.
     Console.WriteLine("Main() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId);
      // Invoke Add() on a secondary thread.
    BinaryOp b = new BinaryOp(Add);
  IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null);
  // This message will keep printing until
// the Add() method is finished.
while(!iftAR.IsCompleted)
 {
  Console.WriteLine("Doing more work in Main()!");
    Thread.Sleep(1000);
}
 // Now we know the Add() method is complete.
  int answer = b.EndInvoke(iftAR);
     Console.WriteLine("10 + 10 is {0}.", answer);
    Console.ReadLine();
     } 

     static int Add(int x, int y)
     {
      // Print out the ID of the executing thread.
         Console.WriteLine("Add() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
          // Pause to simulate a lengthy operation.
        Thread.Sleep(5000);
       return x + y;
        }

CASE 2 code:If we replace the while loop with foll code:

while (!iftAR.AsyncWaitHandle.WaitOne(1000, true))
 {
 Console.WriteLine("Doing more work in Main()!");
}

CASE 3 code:If we replace the while loop from CASE 1 with foll code and add the AddComplete method:

 while (!isDone)
   {
       Thread.Sleep(1000);
       Console.WriteLine("Working....");
      }   

 static void AddComplete(IAsyncResult itfAR)
   {
  Console.WriteLine("AddComplete() invoked on thread {0}.",         Thread.CurrentThread.ManagedThreadId);
 Console.WriteLine("Your addition is complete");
    isDone = true;
   }


Download usage.criteria.for.iasyncresult.iscompleted.iftar.asyncwaithandle.waitone.and.asynccallback.zip
Direct Link


Download


Download usage.criteria.for.iasyncresult.iscompleted.iftar.asyncwaithandle.waitone.and.asynccallback.zip
Mediafire


Download


Download usage.criteria.for.iasyncresult.iscompleted.iftar.asyncwaithandle.waitone.and.asynccallback.zip
Hulkload


Download

Both comments and pings are currently closed.

Comments are closed.