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.
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? 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
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.
If you start using async-await
approach in your code - be aware that async
will spread over whole pipeline of your application.
So
How should I avoid changing my API call async, just for the sake of Logger? What are other possibilities of making this work?
Answer: Do not use async
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?
Answer: Benefit is that during waiting, UI will be "responsive" - user for example will be able to move window of the application on another screen or minimize it.
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: same as previous answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.