TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Tarik Palic
NA
17
1.5k
Log to database on another thread
Feb 12 2017 3:50 AM
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.
Reply
Answers (
2
)
Explain FUNC,ACTION and PREDICATE with real-time examples
Combined script file output failed unexpectedly in c# ashx