Skip Skip - 4 years ago 129
C# Question

Async library method usage in non-async methods

I have created a logging library and the log method returns an error number (PK), upon making an entry into DB, which I notify to users as part of the error message on their UI. They further use that key as a reference when they talk to support team.

And I have an async method for doing the same, as below:

public class Logger
{
public async Task<string> LogAsync(Exception ex)
{
return await DoLogAsync(ex);
}

// some private method, with multiple optional parameters
private Task<string> DoLogAsync(Exception ex)
{
return Task.Run(() => Log(ex));
}
}


Note: I admit, this async version is nothing but simply wraps the synchronous method, Log(), in Task.Run. I am not sure, what else should be done!!

Now, i’m planning to use the above Log() method, in all my APIs, like below:

public Result<MyObject> Get()
{
var result = new Result<MyObject>();

try
{
throw new DivideByZeroException();
}
catch (DivideByZeroException ex)
{
string errorId = await _logger.LogAsync(ex);
response.AddErrorMessage("Please Contact Admin with this error #"+errorId);
}

return result;
}


In order to make above work, I need to make the API method async, since i am awaiting the logger call.


  1. How should I avoid changing my API call async, just for the sake of Logger? What are other possibilities of making this work?

  2. Do you think,
    LogAsync()
    would really be beneficial? My UI thread will be waiting for the error number to be returned anyways, so why not just call the sync method?

  3. There are few
    Log()
    methods, which doesn’t need an error number, in return, kind of log-and-forget. Do you think, async versions, will be helpful in such scenarios, because UI won’t expect anything back?



Answer: For the question 1, this works: Waiting for async/await inside a task

Also for 2, and 3, having ADO.Net implementations make much sense, rather than Task.Run

Answer Source

If you're using Web API I would not go for an async Log method if the method is not truly async. Have a look at this answer from Stephen Cleary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download