Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with HttpTaskAsyncHandler

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?

like image 401
DarthVader Avatar asked Aug 09 '12 03:08

DarthVader


2 Answers

A few points:

  • You can 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.
  • There are several convenience methods available, e.g., Task.FromResult, if you don't need the overhead of an async method.
  • Only make a 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");
  }
}
like image 129
Stephen Cleary Avatar answered Oct 26 '22 21:10

Stephen Cleary


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.

like image 28
Fil Avatar answered Oct 26 '22 21:10

Fil