Async/Await & AsyncController?

2019-05-04 17:15发布

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?

2条回答
不美不萌又怎样
2楼-- · 2019-05-04 17:35

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.

查看更多
趁早两清
3楼-- · 2019-05-04 17:56

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);
    }
查看更多
登录 后发表回答