Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8089497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T19:24:47+00:00 2026-06-05T19:24:47+00:00

I am comfortable with executing synchonous work before calling the inner handler’s SendAsync(), and

  • 0

I am comfortable with executing synchonous work before calling the inner handler’s SendAsync(), and executing synchronous work after the inner handler has completed via a completion. e.g:

protected override Task<HttpResponseMessage> SendAsync( 
    HttpRequestMessage request, CancellationToken cancellationToken) 
{ 
    // do some sync work before inner handler here 

    var sendTask = base.SendAsync(request, cancellationToken); 
    return sendTask.ContinueWith( 
        task => { // do some sync work afterwards here }); 
} 

However, I now need to call an IO bound operation from within a delegating handler. The IO bound operation is already wrapped up as a Task<bool>. I need to use the result to determine whether to continue on to the inner handler.

An example would be making a network call to authorize a request. I have to do this to integrate with an existing system. In general, I think there are valid scenarios for this problem, and it should have a workable solution.

What’s the right way to implement SendAsync in this case, so that I execute the IO bound Task asynchronously and then continue to asynchronously execute the inner handler?

The key point is that I want to be certain that the request thread is not left blocked at any point.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T19:24:49+00:00Added an answer on June 5, 2026 at 7:24 pm

    OK, I think I have this cracked. I’m illustrating this with an authentication scenario: I want to authenticate a user asynchronously and use the result to decide whether to return a 401 or continue with the message handler chain.

    The central problem is that you cannot call the inner handler SendAsync() until you have the result from the asynchronous authentication.

    The key insight for me was to use a TaskCompletionSource (TCS) to control the flow of execution. This enabled me to return the Task from the TCS and set a result on it whenever I liked – and most importantly to delay the call the SendAsync() until I know I need it.

    So, I set up the TCS and then started a task to do the authorization. In the continuation to this, I look at the result. If authorized, I invoke the inner handler chain and attach a continuation to this (avoiding any thread blocking) that completes the TCS. If authentication fails I just complete the TCS there and then with a 401.

    The result of this is that both asynchronous tasks are executed in turn without any thread blocking. I load tested this and it seems to work just fine.

    It’s all much nicer in .NET 4.5 with the async/await syntax though… although the approach with the TCS is still basically happening under the covers, the code is much simpler.

    Enjoy!

    The first snippet was built on .NET 4.0 with the Web API Beta – the second on .NET 4.5/Web API RC.

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
    
        // Authorize() returns a started
        // task that authenticates the user
        // if the result is false we should
        // return a 401 immediately
        // otherwise we can invoke the inner handler
        Task<bool> authenticationTask = Authorize(request);
    
        // attach a continuation...
        authenticationTask.ContinueWith(_ =>
        {
            if (authenticationTask.Result)
            {
                // authentication succeeded
                // so start the inner handler chain
                // and write the result to the
                // task completion source when done
                base.SendAsync(request, cancellationToken)
                    .ContinueWith(t => taskCompletionSource.SetResult(t.Result));
            }
            else
            {
                // authentication failed
                // so complete the TCS immediately
                taskCompletionSource.SetResult(
                    new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
        });
    
        return taskCompletionSource.Task;
    }
    

    Here is a .NET 4.5 / Web API Release Candidate version which is a lot sexier with the new async/await syntax:

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Authorize still has a Task<bool> return type
        // but await allows this nicer inline syntax
        var authorized = await Authorize(request);
    
        if (!authorized)
        {
            return new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("Unauthorized.")
            };
        }
    
        return await base.SendAsync(request, cancellationToken);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

After building a service that launches an interactive processes in a user's session via
After developing for iOS for some time now, I have gotten comfortable with the
I'm getting comfortable with the Lithium framework, and was wondering if there were any
I am quite comfortable with generics and such, but in this special case I
Trying to get comfortable with jQuery and I have encountered some sample code that
Since I'm more comfortable using Eclipse, I thought I'd try converting my project from
I have been quite comfortable with windows-services, I have been practicing since from last
I'm prettyd comfortable with Git, an I've been using it for over a year
I am getting comfortable with using plists for initializing my app. I now want
I am now quite comfortable using autosizing masks in IB but there are two

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.