Reputation: 148664
A bit not relevant for today's technology but I saw another way of working with Tasks in APM environment , besides the Task.FromAsync
Async Handler in asp.net :
public class Handler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
//...
}
public void EndProcessRequest(IAsyncResult result)
{
//...
}
}
context
parameter is the actual context which I can access/
(or pass to another beginXXX operation) request and response.cb
is for me to execute/
(or pass to another beginXXX operation) when the operation finished.Question
But what is the object extraData
is doing in the signature of the method ?
It is not that I get some state from the framework , on the contrary - I create state and pass it forward so that my EndXXX could cast result.AsyncState
to T and use that data.
So why is it there?
Upvotes: 0
Views: 342
Reputation: 5832
In short, it is required by the APM Pattern, which IHttpAsyncHandler
is following. You don't need it here, but there are cases (of pattern usage, not handler usage) when it is useful to correlate callbacks.
Update:
Here's the recommended way to use Task
s in APM:
public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
{
Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
Task<string> f = Task<string>.Factory.StartNew(_ => Compute(decimalPlaces), state);
if (ac != null) f.ContinueWith((res) => ac(f));
return f;
}
public string Compute(int numPlaces)
{
Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId);
// Simulating some heavy work.
Thread.SpinWait(500000000);
// Actual implemenation left as exercise for the reader.
// Several examples are available on the Web.
return "3.14159265358979323846264338327950288";
}
public string EndCalculate(IAsyncResult ar)
{
Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId);
return ((Task<string>)ar).Result;
}
Please note that the state is passes to task factory, and the resulted task is used as both the argument to the callback and the return value.
Upvotes: 3