Today is the world of multitasking. You work on your laptop/desktop, surf the internet, listen to the songs, check your mails, chat with your friends and do lots of other activities simultaneously. How is this possible. All these tasks work almost independently of each other. In the coding world, it is also possible to allow multiple code logic’s or processes to execute simultaneously. This in technical terms is known as process of Threading.
Threads in C# :
A thread is a way to implement the Threading concept. There can be multiple threads in an application and it allows these processes to take place simultaneously without affecting each other. But 2 or more threads will only not affect each other until they are accessing resources that are independent for each of them. But what happens if they are required to share a common piece of code or access any resource at the same time. This introduces that concept of thread safety.
Thread safety :
Since multiple threads can exist in an application, it is quite possible that they share or use common resources for processing or completing any process. So in case the data or code is being shared by them, it is also possible that 2 or more threads may try to access these resources at the same time. So this situation may result in a state of inconsistent results or a state of deadlock etc.
In a simple language, consider a situation when a person is using an ATM machine and too many users try to enter the same area where the machine is located. Imagine, there is no mechanism or door to isolate or secure you from the rest of the people waiting to access the ATM machine. Then all of them will try to access the machine at the same, which may not allow you to or any other user to withdraw from the machine.
So to avoid same kind of problem in the code, it is required to write the code in THREAD SAFE manner. This is know as Thread Safety.
Important Point : A main function in any windows or console application is also a thread in itself. Further threads can be created in it which results in a multi-threaded application.