I am a C # programmer, I missed some snippets here and there when it comes to the fact that you are very good at things, and now I came across something that I could not find to answer the SO. I'm trying to better understand thread safety in C #, but let me first point out the context.
I am currently developing a Windows service that shuts down and does some monitoring work based on the schedule that is in the SQL Server database. It will track some servers, making http requests to several "client servers", the client installed on these servers will respond with the requested information.
Since this monitoring service may be quite busy, I configured it to use each "scheduled instruction" in a new thread when it is scheduled to do this work. This is done so that my timer continues to tick in a good way, ready to release the next command to the next "client server".
Part of each command is that it must be registered in a database that was executed successfully, and what was the answer, and so on. Now I have a public static class Logger in the monitoring service, I think this is convenient, because now I can easily call it that Logger.Log(... ) whenever I need to write things. This logging occurs in this class through EF to the SQL Server database.
It all sounds very cool to me, and I'm quite happy with how it all works, but so far I have not tested anything. The problem that I have in all of this is that my brain tells me that since my logger class is static and, in my understanding, it is created only once? - if more than 1 thread tries to call Logger.Log(.. ) at the same time, bad things will happen to my monitoring service.
Is there anyone here who can enlighten me? I think right or wrong? And if you know the answer, please explain it clearly, because I would like to understand it. :)
Update:
Thanks for the answers so far, everything is becoming clearer, as people ask for more information about the Log method, and I am not on my development PC at the moment, I will try to explain how it works in more detail.
The whole Log method is to add an entry to the SQL database through EF based on data from some previously created objects that are passed to the method as parameters. The database context is created as a static private variable in a static class. The reason for this is that I do not need to continue to use expressions in my overloads.
multithreading c # static thread-safety class
Mathijs flietstra
source share