Reputation: 22672
How can I wrap the result of an async method into a my own wrapper class (MyEnvelop) and return it like a task?
I use a custom Envelope class for returning results from my Data Access component back to Business Layer. This works fine with sync methods, but how can I return the result of type MyEnvelope in async mode?
Updated the code sample:
public async Task<MyEnvelope<Customer>> FindAsync(params object[] keyValues)
{
using (var nw = new NWRepository())
{
Customer result = await nw.DoSomethingAsync<Customer>(keyValues);
return // here I would like to return new MyEnvelope<Customer>(result)
// wrapped in Task as shown in the signature
}
}
Upvotes: 0
Views: 760
Reputation: 12410
Can't be done because you need the task to resolve before you can pass it to MyEnvelope
. The closest you can get is to remove the async/await
keywords which unwrap the task and get Task<Customer>
.
public Task<Customer> FindAsync(params object[] keyValues)
{
using (var nw = new NWRepository())
{
return nw.DoSomethingAsync<Customer>(keyValues)
}
}
Upvotes: 0
Reputation: 15797
What you want to do is that:
public async Task<MyEnvelope<Customer>> FindAsync(params object[] keyValues)
{
using (var nw = new NWRepository())
{
Customer c = await nw.FindAsync<Customer>(keyValues);
return new MyEnvelope<Customer>(c);
}
}
you then call the method like that:
MyEnvelope<Customer> customer = await FindAsync(p1, p2, p3);
Remember await
will return the Result
of a Task<T>
which is of type T
not the Task
object itself.
Upvotes: 3