How to make async action method that call to external c# dll

Viewed 41

I have action method in my ASP.NET Core Web API project that call to function in external C# dll. These functions do calculations to the data that I pass to them and return an output to me. How I do my action function asynchronous? And is it even necessary to do so?

      [HttpPost]       
    public IActionResult SetClac([FromBody] CalcRequest calcRequest)
    {
        try
        {
            
            IClacSdk clacSdk = new CalcSdk();
            ClacResult clacResult = clacSdk.clac(calcRequest.id , calcRequest.username)
                                                                            
            CustomeResponse customeResponse = new CustomeResponse()
            {
                ErrorDescription = clacResult.ErrorDescription,
                ErrorNum = clacResult.ErrorNum,
                ClacResult = clacResult.Result
            };
            return Ok(customeResponse);
        }
         catch (Exception exc)
        {
            return StatusCode(500, (GetErrorFormat(exc)));
        }
        
    }
1 Answers

How i do my action function asynchronous?

You can wrap them in Task.Run (though it will not make the operation "truly" async). I.e.:

ClacResult clacResult = await Task.Run(() => clacSdk.clac(calcRequest.id , calcRequest.username));

And is it even necessary to do so?

No. Even more - in context of ASP.NET Core in general case it is recommended not to do so cause it can negatively affect server throughput (though if you have several calculation which you want to perform in parallel and individual response time is a priority you can leverage Task.Run).

If you want to dig dipper there are multiple resources to start:

  1. Asynchronous Programming in .NET - Introduction, Misconceptions, and Problems
  2. Official documentation (in this context this one discussing I/O-bound and CPU-bound code can be useful)
  3. Articles by Stephen Cleary (especially There Is No Thread one which personally I find very interesting)
Related