3

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 ); 
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

2 Answers2

5

The task factory has a method just for that: Task.Factory.FromAsync.

var task = Task.Factory.FromAsync(
    contactGroupServices.BeginDeleteContact(contactToRemove.Uri),
    ar =>
    {
        try
        {
            _contactGroupServices.EndDeleteContact(ar);
        }
        catch (RealTimeException rtex)
        {
            Console.WriteLine(rtex);
        }
    });

You can block until it's done by calling task.Wait, but that will deadlock in most cases (if called from a UI thread, for example).

You might want to put it inside an asynchronous method:

async Task M()
{
    ...
    await Task.Factory.FromAsync(
        contactGroupServices.BeginDeleteContact(contactToRemove.Uri),
        ar =>
        {
            try
            {
                _contactGroupServices.EndDeleteContact(ar);
            }
            catch (RealTimeException rtex)
            {
                Console.WriteLine(rtex);
            }
        });
    ...
}
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
3

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);
slava
  • 1,901
  • 6
  • 28
  • 32