等待 IAsyncResult 函数完成
Wait IAsyncResult function until complete
我需要创建等待 IAsyncResult 方法完成的机制。
我怎样才能做到这一点?
IAsyncResult result = _contactGroupServices.BeginDeleteContact(
contactToRemove.Uri,
ar =>
{
try
{
_contactGroupServices.EndDeleteContact(ar);
}
catch (RealTimeException rtex)
{
Console.WriteLine(rtex);
}
},
null );
我不知道这个方法的目标是什么_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);
任务工厂有一个方法: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);
}
});
...
}
我需要创建等待 IAsyncResult 方法完成的机制。 我怎样才能做到这一点?
IAsyncResult result = _contactGroupServices.BeginDeleteContact(
contactToRemove.Uri,
ar =>
{
try
{
_contactGroupServices.EndDeleteContact(ar);
}
catch (RealTimeException rtex)
{
Console.WriteLine(rtex);
}
},
null );
我不知道这个方法的目标是什么_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);
任务工厂有一个方法: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);
}
});
...
}