4

I have an existing Business Library, which I want to expose using Web API. My existing business classes looks like

public class Business
{
    public bool DoSomeBusiness()
    {
        //Performing long running  DB operations
        return true;
    }
    //Other methods
}

I am writing a Web API method like following code and using asyn/await for better scalability.

public class SampleController : ApiController
{
    Business _business;
    public ValuesController(Business business)
    {
       _business = business;
    }
    public async Task<HttpResponseMessage> Get()
    {
       var result= await Task.Run(() => _business.DoSomeBusiness());
       return Request.CreateResponse(HttpStatusCode.OK, result);
    }
}

Is this approach correct? Will I get the real benefit of the asynchronous behaviour? I don’t want to change my existing business layer implementation to make them task based.

Simon Karlsson
  • 3,868
  • 18
  • 36
  • 1
    A chain of await calls should end with a .NET Framework BCL async method. Your `DoSomeBusiness` is still a method in sync, so it won't give you any better. It is very easy to get wrong understanding of async/await, so try to dig further you'd better find a good book. – Lex Li Jan 23 '16 at 13:31
  • What are you using for db operations? Entity Framework? Raw ADO.NET? Add an example db call to your sample code I should be able to steer you in the right direction. – Todd Menier Jan 23 '16 at 15:27
  • We are using ADO.NET for the db calls. –  Jan 26 '16 at 10:55

1 Answers1

9

This accomplishes nothing. If it did, ASP.NET could just run your action in a Task.Run call automatically and achieve better scalability.

You can't cheat this. You need to use async all the way down to the IOs you're making. This infects everything which is why this should be done when needed and not by default.

I'll link you two basic posts about making this choice because right now you do not understand the topic enough to make the choice:

https://stackoverflow.com/a/25087273/122718 Why does the EF 6 tutorial use asychronous calls? https://stackoverflow.com/a/12796711/122718 Should we switch to use async I/O by default?

Community
  • 1
  • 1
usr
  • 162,013
  • 33
  • 219
  • 345