此 MSDN 页面有以下示例: 目的是包装无法在各种Func<T1, T2, T3>
重载中表示的 APM 样式任务。
static Task<String> ReturnTaskFromAsyncResult()
{
IAsyncResult ar = DoSomethingAsynchronously(); // <-- If this is an APM method, it's a bad example since most APM methods have a parameter for callback and state.
Task<String> t = Task<string>.Factory.FromAsync(ar, _ =>
{
return (string)ar.AsyncState;
});
return t;
}
我的问题与功能有关DoSomethingAsynchronously();
。我见过的大多数 APM 函数都需要参数回调和状态,这在本示例中是缺失的。
问题: “DoSomethingAsynchronously”中的回调和状态参数会发生什么变化
我需要做什么才能正确调用类似的函数?就我而言,我正在尝试像这样包装 Azure Table 调用
Task CreateAsync(CloudTable tbl, CancellationToken token, object state)
{
ICancellableAsyncResult result = tbl.BeginCreate(null, state); // Incorrect
token.Register((o) => result.Cancel(), state);
Task<bool> t = Task.Factory.FromAsync(result, _ =>
{
return (bool)result.AsyncState;
});
return t;
}
Task<bool> ExistsAsync(CloudTable tbl, CancellationToken token, object state)
{
ICancellableAsyncResult result = tbl.BeginExists(null, state); // Incorrect
token.Register((o) => result.Cancel(), state);
Task<bool> t = Task.Factory.FromAsync(result, _ =>
{
return (bool)result.AsyncState;
});
return t;
}