This is the generic pattern with which to implement the classic APM programming model:
protected override IAsyncResult BeginTrack(TrackingRecord record, TimeSpan timeout, AsyncCallback callback, object state)
{
Task result = Task.Factory.StartNew(
(taskState) =>
{
// ... your async work here ...
},
state);
if(callback != null)
{
result.ContinueWith((t) => callback(t));
}
return result;
}
protected override void EndTrack(IAsyncResult asyncResult)
{
// Call wait to block until task is complete and/or cause any exceptions that occurred to propagate to the caller
((Task)asyncResult).Wait();
}
If the EndXXX method returned a result you would actually return the Result
property of the Task
instead of just calling Wait
. For example:
protected override int EndAwesomeCalculation(IAsyncResult asyncResult)
{
// This will block until the result is available and/or cause any exceptions that occurred propagate to the caller
return ((Task<int>)asyncResult).Result;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…