Search code examples
c#.netasynchronousasync-awaitiasyncresult

Wait IAsyncResult function until complete


I need to create mechanism which waits IAsycnResult method till complete. How can i achieve this ?

IAsyncResult result = _contactGroupServices.BeginDeleteContact(
  contactToRemove.Uri,
  ar =>
      {
      try
         {
           _contactGroupServices.EndDeleteContact(ar);
         }
      catch (RealTimeException rtex)
         {
            Console.WriteLine(rtex);
         }
      },
      null ); 

Solution

  • I dont have any idea what is the goal of this method _contactGroupServices.BeginDeleteContact . But lets try to write template for it

    Func<object> doWork = () =>
    {
        return _contactGroupServices.BeginDeleteContact(<your parameters>)
    
    };
    
    
    AsyncCallback onWorkDone = (ar) =>
    {
        //work done implementation
    };
    
    IAsyncResult asyncResult = doWork.BeginInvoke(onWorkDone, null); 
    
    asyncResult.AsyncWaitHandle.WaitOne();
    
    var result = doWork.EndInvoke(asyncResult);