等待IAsyncResult函数直到完成

时间:2015-05-22 07:51:02

标签: c# .net asynchronous async-await iasyncresult

我需要创建等待IAsycnResult方法直到完成的机制。 我怎样才能实现这一目标?

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

2 个答案:

答案 0 :(得分:3)

任务工厂只有一个方法:Task.Factory.FromAsync

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

您可以通过调用task.Wait来阻止它,但是在大多数情况下会死锁(例如,如果从UI线程调用)。

您可能希望将其放在异步方法中:

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

答案 1 :(得分:0)

我不知道这个方法_contactGroupServices.BeginDeleteContact的目标是什么。但是让我们尝试为它编写模板

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