I'm a self taught C# programmer, I've missed some bits here and there when it comes to having a very thorough understanding about things, and now I've stumbled across something I haven't been able to find an answer to on SO. I'm trying to get a better understanding about thread safety in C#, but let me first specify the context.
I'm currently developing a Windows service which goes off and does some monitoring work based on a schedule which resides in a SQL Server database. It is going to monitor some servers by making http requests to a number of "client servers", a client installed on those servers will respond with the requested information.
As this monitor service might get quite busy, I have set it up to stick every "scheduled instruction" in a new thread when it is scheduled to do the work. This is to make sure my timer keeps ticking along nicely, ready to fire off the next instruction to the next "client server".
A part of each instruction is that is has to log in the database that it has executed successfully and what the response was and so on. Now I have in my monitor service a public static class Logger
, I believe this is handy as I can now easily call it this way Logger.Log(... )
whenever I need to log things. This logging happens in this class through EF into the SQL Server database.
To me this all sounds really cool, and I'm quite happy with how it all works, but I haven't load tested anything as of yet. The problem I have with all of this is that my brain tells me that since my logger class is static -and according to my understanding therefore it is only instantiated once?- if more than 1 thread tries to call Logger.Log(.. )
at the exact same time, bad things will happen to my monitor service.
Is there someone here who can enlighten me? Is my thinking right or wrong? And if you know the answer, please explain it clearly because I would love to understand it. :)
Update:
Thanks for responses up till now, things are getting clearer, as people are asking more details about the Log
method, and I'm not at my development PC at the moment, I will try to explain the way it works in a bit more detail.
All the Log
method does is add a record to the SQL database through EF based on data from some previously instantiated objects which are passed in to the method as parameters. The database context is instantiated as a static private variable on the static class. The reason for this is so that I don't have to keep putting using statements in my overloads.