4

Do you have to inherit from AsyncController when you're using Async/Await in your controller or will it not truly be asynchronous if you use Controller? How about Asp.net web api? I don't think there is a AsyncApiController. Currently i'm just inheriting from controller and its working but is it truly async?

1

2 Answers 2

6

The XML comment for the AsyncController class in MVC 4 says

Provided for backward compatibility with ASP.NET MVC 3.

The class itself is empty.

In other words, you don't need it.

Sign up to request clarification or add additional context in comments.

Comments

0

In terms of Web API, you don't need a Async controller base class. All what you need to do is to wrap your return value in a Task.

For example,

    /// <summary>
    /// Assuming this function start a long run IO task
    /// </summary>
    public Task<string> WorkAsync(int input)
    {
        return Task.Factory.StartNew(() =>
            {
                // heavy duty here ...

                return "result";
            }
        );
    }

    // GET api/values/5
    public Task<string> Get(int id)
    {
        return WorkAsync(id).ContinueWith(
            task =>
            {
                // disclaimer: this is not the perfect way to process incomplete task
                if (task.IsCompleted)
                {
                    return string.Format("{0}-{1}", task.Result, id);
                }
                else
                {
                    throw new InvalidOperationException("not completed");
                }
            });
    }

In addition, in .Net 4.5 you can benefit from await-async to write even more simple codes:

    /// <summary>
    /// Assuming this function start a long run IO task
    /// </summary>
    public Task<string> WorkAsync(int input)
    {
        return Task.Factory.StartNew(() =>
            {
                // heavy duty here ...

                return "result";
            }
        );
    }

    // GET api/values/5
    public async Task<string> Get(int id)
    {
        var retval = await WorkAsync(id);

        return string.Format("{0}-{1}", retval, id);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.