I have created a CommonUtils.cs file containing 5 static functions (So that I can just "copy" this .cs for other projects in Visual Studio since I develop different C# applications) along with that I have many source files.
Now, I have compiled my project to a DLL. This dll is hosted via IIS server as an application. Many customers use this dll to perform something, say they generate a report.
I have been informed that "static functions" must not be used generously in this context and they should be applied, a "locking" mechanism since without lock, multiple threads of a single instance of program or multiple instances of a program, both can behave unexpectedly. Is it true?
I have been informed that "static functions" must not be used
generously in this context and they should be applied, a "locking"
mechanism since without lock, multiple threads of a single instance of
program or multiple instances of a program, both can behave
unexpectedly. Is it true?
Let's break it piece by piece. What is a static class?
A static class is basically the same as a non-static class, but
there is one difference: a static class cannot be instantiated. In
other words, you cannot use the new keyword to create a variable of
the class type. Because there is no instance variable, you access
the members of a static class by using the class name itself.
How CLR treats a static class?
As is the case with all class types, the type information for a static
class is loaded by the .NET Framework common language runtime (CLR)
when the program that references the class is loaded. The program
cannot specify exactly when the class is loaded. However, it is
guaranteed to be loaded and to have its fields initialized and its
static constructor called before the class is referenced for the first
time in your program. A static constructor is only called one time,
and a static class remains in memory for the lifetime of the
application domain in which your program resides.
Now why we may need locking?
Basically, locking is needed when we have race conditions. When someone may read data that someone else may alter them in the same time. Two separate threads have access to a shared resource and there isn't any mechanism to prevent this. In order you take an answer to your question, you have at first to answer another question.
Does your static methods access shared resources and there might be any race condition? If that's true, then you need to use locking. Otherwise, it is not needed.
For further information about static classes, please have a look here.
While if you need more information about thread synchronization techniques, please have a look here.
Functions are immutable so you don't need to synchronize when calling a function. Function parameters are mutable but each invocation has it's own local copy. No need to synchronize either.
Synchronization is required when multiple thread work on the same data and there is at least one writer. This is about any variable that is shared between threads. Care is required for static variables and any instance variable reachable by a static variables.
It sounds like you have a class library. Here are Microsoft's guidelines for class libraries that need to support multi threading:
Avoid the need for synchronization, if possible. This is especially true for heavily used code. For example, an algorithm might be adjusted to tolerate a race condition rather than eliminate it. Unnecessary synchronization decreases performance and creates the possibility of deadlocks and race conditions.
Make static data (Shared in Visual Basic) thread safe by default.
Do not make instance data thread safe by default. Adding locks to create thread-safe code decreases performance, increases lock contention, and creates the possibility for deadlocks to occur. In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the .NET Framework class libraries are not thread safe by default.
Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility of threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests. Furthermore, if static data are synchronized, calls between static methods that alter state can result in deadlocks or redundant synchronization, adversely affecting performance.
Copied from https://msdn.microsoft.com/en-us/library/1c9txz50(v=vs.110).aspx
Explanation for "LOCK" From MSDN says:
The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released
References:
https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Its better to use LOCK in Multithreading than creating Static functions everytime.
Related
I am a newbie in .NET and have many confusions regarding the same. If for every request in a dotnet MVC web application a thread is created and inside that thread if we access static variables, then, will the static variables inside all the threads have common memory or will every single thread contain separate static memory variables?
I don't have any code currently.
Following is a bit of a simplification, but should provide enough context to answer your question.
The memory model for .NET is such that memory is generally shared across threads and can be done so without synchronizing access. Thus, if you have some class A, both its instance and static members can be accessed across threads. That is, of course, problematic because multiple threads accessing either could result in concurrency issues or corrupt state.
That said, it is possible to prevent this corruption in a few ways
use lock or some other form of mutual exclusion on both static and instance members
use statics with ThreadLocal or [ThreadStatic]
and, if state must be shared across threads, copy it so threads are accessing memory that (hopefully) the original thread won't touch
There are pros and cons to these. It is generally better to have no cross-thread dependencies. In the context of ASP.NET this is especially true. Ideally you want your APIs and/or web page renders to be completely independent with other calls and across calls.
If you find yourself needing static members (without ThreadLocal<T> or [ThreadStatic]) stick to making only read accesses (no writes) against these fields. But even then, the lifecycle of the static field matters; for example, if the static is initialized after requests start accessing the fields, you'll have trouble.
As an API designer, does it make sense to perform lock checks to ensure that the object state is not invalidated by the caller?
Consider a Grid3D data structure which must resize itself each time its Width, Heigth, or Depth is changed. If a caller is modifying the Grid3D from multiple threads, the Grid could be resizing while a new resize attempt is made and this would invalidate the object state or throw an exception.
This can be overcome by using locks to provide mutual exclusion to the resize function, and it could happen either within the API (that is, the class definition of Grid3D) or it can happen in the application where Grid3D is used.
If it is correct to lock inside the Grid3D class definition, it stands to say that thread synchronization should be considered for all API development. In many cases (certainly many examples online including StackOverflow) do not consider synchronization in API-level classes.
So, where is the correct place to perform locking? Under what conditions should the API-level be concerned with locking?
It's your design decision, You can create a thread safe class or you can delegate the task of using it in thread safe manner to the one who uses it.
Usually libraries does not provide thread safe instances of classes when they are not intended to be used in multi-threaded environment. If the main usage of your class is in multi-threaded environment you should handle the thread-safety.
You can see this quote million of times in MSDN
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
this means that instances of the class are not meant to be used by default in multi-thread environment but you can see also classes that support built in synchronization by default and are ready to be used in multi-threaded environment.
As I see the Grid3D is meant to be a UI component and usually UI components are built to be used just by the thread that have created them.
It depends on whether the API is supposed to be thread-safe or not. If it is, then API layer should be concerned with locking, otherwise it should not.
As an example have a look at System.Threading.Thread and System.Array classes. The Thread is thread-safe and it is documented so (see Thread Safety section), while Array is not thread-safe and it is noted in documentation that its “…Any instance members are not guaranteed to be thread safe”.
I have a component registered in Castle Windsor as a singleton. This object is being used in many other places within my application which is multithreaded.
Is it possible that the two objects will invoke the same method from that singleton at the same time or 'calling it' will be blocked until the previous object will get result?
Thanks
You can call a Singleton object method from different threads at the same time and they would not be blocked if there is no locking/ synchronization code. The threads would not wait for others to process the result and would execute the method as they would execute methods on separate objects.
This is due to the fact that each thread has a separate stack and have different sets of local variables. The rest of the method just describes the process as to what needs to be done with the data which is held the variables/fields.
What you might want to take care of is if the methods on the Singleton object access any static methods or fields/variables. In that case you might need to work on synchronization part of it. You would need to ensure multi-threaded access to shared resources for the execution of the method to be reliable.
To be able to synchronize, you might need to use lock statement or other forms of thread synchronization techniques.
You might want to refer to this article from Wikipedia which provides information on C# thread local storage as well.
You can call the same method or different methods on one object simultaneously from different threads. In the specific methods you'll need to know when sensitive variables are being accessed (mostly when member-variables are changing their values) and will need to implement locking on your own, in order to solve lost updates and other anomalies.
You can lock a part of a code with the lock-statement and here an article on how Thread-Synchronization works in .Net.
The normal version of Singleton may not be thread safe, you could see different implementation of thread safe singleton here.
http://tutorials.csharp-online.net/Singleton_design_pattern:_Thread-safe_Singleton
I have a 3rd party library that offers a class. Their documentation says:
Thread Safety
Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.
I did some testing where I created 100 threads. Indeed there are thread safety issues if I pass the same object to all 100 threads, but those problems appear to go away if each thread creates its own instance of the class.
I'm using .NET 4.0 here. In my application there are multiple threads that will want to use this class, but I don't want to create and destroy the objects more than necessary (they should live for the lifetime of the application), so I want one per thread. Is this an appropriate use of the ThreadLocal<T> class? If not, what is the standard way to handle this?
Edit:
Some more information about the 3rd party class. It's a communication library and opens a communication link to another process, either on this computer or another computer. The other end of the communication link is designed to accept concurrent connections. Therefore I shouldn't need to synchronize the method calls on my end by using locks. However, each instance is not thread safe.
Assuming you don't need the objects to interact with each other at all, ThreadLocal<T> is a very good choice here. It obviously doesn't work if modifications made in one thread are meant to be seen in another thread, just safely.
Yes, it will create one object per thread - but unless creating the objects is really expensive, you're likely to have on the order of hundreds of instances, which in most cases is absolutely fine.
One classic example of this is System.Random:
You don't want to create instances on an ad hoc basis, as if you're not careful you'll end up with multiple instances with the same seed
It's definitely not thread-safe.
So you could do something like:
public static class RandomProvider
{
private static readonly Random seedProvider = new Random();
private static readonly ThreadLocal<Random> threadLocal =
new ThreadLocal<Random>(InitializeNewRandom);
public static Random GetRandomForThread()
{
return threadLocal.Value;
}
private static Random InitializeNewRandom()
{
lock(seedProvider)
{
return new Random(seedProvider.Next(int.MaxValue));
}
}
}
An alternative would be to write a thread-safe proxy class which used locking for each operation - but that still has issues if you have multiple operations which you wish to execute "atomically" (i.e. without interleaving other calls).
I think that making a wrapper above this class which blocks all operations with Monitors( lock keyword) or other thread blocking sync construct can help.
But it does not guarantee absence of possible deadlocks and race conditions. Without complete rewrite of the original class and its consumers you may still run into a problem.
You can't make unsafe thing safe and unsecure thing secure in postprocessing. Such qualities must be considered at first and this is even not your library.
In many MSDN documents, this is written under the Thread Safety heading;
"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."
for example; here
can someone explain it please in a rather simple way?
Thank you :)
Eric Lippert has an excellent blog post about this. Basically it's somewhat meaningless on its own.
Personally I don't trust MSDN too much on this front, when I see that boiler-plate. It doesn't always mean what it says. For example, it says the same thing about Encoding - despite the fact that we all use encodings from multiple threads all over the place.
Unless I have any reason to believe otherwise (which I do with Encoding) I assume that I can call any static member from any thread with no corruption of global state. If I want to use instance members of the same object from different threads, I assume that's okay if I ensure - via locking - that only one thread will use the object at a time. (That's not always the case, of course. Some objects have thread affinity and actively dislike being used from multiple threads, even with locking in place. UI controls are the obvious example.)
Of course, it becomes tricky if objects are being shared unobviously - if I have two objects which each share a reference to a third, then I may end up using the first two objects independently from different threads, with all the proper locking - but still end up corrupting the third object.
If a type does advertise itself to be thread safe, I'd hope that it would give some details about it. It's easy if it's immutable - you can just use instances however you like without worrying about them. It's partially or wholly "thread-safe" types which are mutable where the details matter greatly.
You may access any public static member of that class from multiple threads at the same time, and not disrupt the state of the class. If multiple threads attempt to access the object using instance methods (those methods not marked "static") at the same time, the object may become corrupted.
A class is "thread-safe" if attempts to access the same instance of the class from multiple threads at the same time does not cause problems.
An object being "thread safe" means that if two threads are using it at (or very near, on single-CPU systems) the exact same time, there's no chance of it being corrupted by said access. That's usually achieved by acquiring and releasing locks, which can cause bottlenecks, so "thread safe" can also mean "slow" if it's done when it doesn't need to be.
Public static members are pretty much expected to be shared between threads (Note, VB even calls it "Shared"), so public statics are generally made in such a way that they can be used safely.
Instance members aren't usually thread-safe, because in the general case it'd slow things down. If you have an object you want to share between threads, therefore, you'll need to do your own synchronization/locking.
To understand this, consider the following example.
In MSDN description of .net class HashSet, there is a part that says about the thread safety. In the case of HashSet Class, MSDN says “Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.”
Of cause we all know the concept of race conditions and deadlocks, but what does Microsoft wants to say in simple English?
If two threads add two values to an “instance” of a HashSet there are some situation where we can get its count as one. Of cause in this situation the HashSet object is corrupted since we now have two objects in the HashSet, yet its count shows only one. However, public static version of the HashSet will never face such a corruption even if two threads concurrently add values.