Hello everyone,I created a simple class library project that should enable me to do logging in my other projects. Now one of the things I wanted to implement was logging the data on a another thread. So I created a function like this:
public async Task LogMessage(string _Message)
{
if (UserID == null)
{
if (RetryLogsList.Count < Configuration.LogHistoryMax)
{
LogToRetryList(_Message);
}
else if (RetryLogsList.Count >= Configuration.LogHistoryMax)
{
foreach (var one_item in RetryLogsList)
{
await Task.Run(() => LogToDatabase(one_item.Message, one_item.Created));
}
RetryLogsList.Clear();
}
}
else
{
if (RetryLogsList.Count > 0)
{
foreach (var one_item in RetryLogsList)
{
await Task.Run(() => LogToDatabase(one_item.Message, one_item.Created));
}
RetryLogsList.Clear();
}
await Task.Run(() => LogToDatabase(_Message));
}
}
This is the function that is called by anyone consuming the logging service like so:
await Log.LogMessage("Some log message");
Now, I don't really understand what happens under the hood. LogToDatabase is a synchronous metod that uses SqlConnection and SqlCommand objects to write data to database, and is being called by asynchronous function with Task.Run.
Is this creating a new thread every time Log.LogMessage() function is called? If so, how are threads managed? More importantly, is this a good option at all?
Thank you for your input.