Satisfy need of thread synchronization in C# multithreading

(Last Updated On: January 13, 2017)

For this C# thread synchronization interview question, we should be answering need of thread synchronization in C# with program example using with and without synchronization.

Answer:

When sharing of resource i.e. file IO and shared memory etc. among multiple threads comes into picture we need thread synchronization. Let’s take a thread program example in which console will be shared by two threads to print a string on it.

Let’s see the output of the below program where we are not synchronizing the printer() function that is used by two threads.

printer() function print a string i.e. “interview sansar is the excellent resource for interview preparation!!!” on cmd console for each thread.

Look at the Output of below program on console. You should find the unwanted output i.e. mixture of both strings.

Output:

interviewinterview sansar is the excellent resource for interview preparation!!!sansar is the excellent resource for interview preparation!!!

 

 

With thread synchronization C# example

When we synchronize the code block of printer() function where printing is going on console,  program will print the correct string for both threads on the console.

Output:

interview sansar is the excellent resource for interview preparation!!!interview sansar is the excellent resource for interview preparation!!!
In below program we have used Object lock to synchronize the code block in printer () function where threads are printing strings on same cmd console.