public class FooHandler : HttpTaskAsyncHandler
{
public override async Task ProcessRequestAsync(HttpContext context)
{
return await new AdRequest().ProcessRequest();
// getting error here. "Return type of async type is void"
}
}
public class FooRequest
{
public async Task<String> ProcessRequest()
{
//return await "foo"; obviously nothing to wait here
}
}
I want to make a async handler and just want to return a string. How can i get this working? and is there a concise reference to work with Async methods and Tasks?
A few points:
await
any Task
, not just ones returned from async
methods.async
methods wrap their returned value into a Task<TResult>
; if there is no return value, they wrap the return itself into a Task
.Task.FromResult
, if you don't need the overhead of an async
method.async
if you have to use await
in it. If you don't need to make the method async
, don't.You may find my async/await intro helpful.
public class FooHandler : HttpTaskAsyncHandler
{
public override Task ProcessRequestAsync(HttpContext context)
{
return new AdRequest().ProcessRequest();
}
}
public class AdRequest
{
public Task<String> ProcessRequest()
{
return Task.FromResult("foo");
}
}
You shouldn't "return" the Task, the compiler will do it implicitly as it is an async function:
public override async Task ProcessRequestAsync(HttpContext context)
{
await new AdRequest().ProcessRequest();
}
public async Task<String> ProcessRequest()
{
return "foo";
}
This is another way, closer to what you were trying to do: (without async/await)
public override Task ProcessRequestAsync(HttpContext context)
{
return new AdRequest().ProcessRequest();
}
public Task<String> ProcessRequest()
{
return Task.Return("foo");
}
A general reference to async
is here
Essentially adding the async
modifier to a method, makes it return a Task
implicitly. If you return an int, it will turn it into a Task<int>
. await
does the opposite, turning a Task<int>
into an int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With