Net multithreading interview questions – Threading Interview Questions in .NET

Net multithreading interview questions: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Threading

Question 1.
What is multi-tasking?
Answer:
It is a feature of modern operating systems with which we can run multiple programs at same time, for example Word, Excel, etc.

Question 2.
What is multi-threading?
Answer:
Multi-threading forms a subset of multi-tasking. Instead of having to switch between programs, this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

Question 3.
What is a thread?
Answer:
A thread is a basic unit to which the operating system allocates processor time.

Question 4.
Did VB6 support multi-threading?
Answer:
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.

Question 5.
Can we have multiple threads in one App domain?
Answer:
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread but can create additional threads from any of its threads.

Note: All threading classes are defined in System. Threading namespace.

Question 6.
Which namespace has threading?
Answer:
‘ Systems. Threading’ has all the classes related to implement threading. Any .NET application which can implement threading has to import this namespace.

Note:NETprogram always has at least two threads running one is the main program and second is the garbage collector.

Question 7.
Can you explain in brief how can we implement threading?
Answer:

Private Sub Forml_Load (ByVal sender As System. Object, ByVal e as
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread (AddressOf Thread1)
Dim pthread2 As New Thread (AddressOf Thread2) 
pthread1.Start ( ) 
pthread2.Start ()
End Sub
Public Sub Threadl ( )
Dim pint count As Integer
Dim pstr As String
Pstr = "This is first thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1
Loop 
End Sub
Public Sub Thread2 ()
Dim pint count As Integer
Dim pstr As String
Pstr = "This is second thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1 
Loop 
End Sub
Note: If you run the sample, you will see that sometimes the first thread runs first and then the second thread. 
This happens because of thread priorities. The first thread is run with highest priority.

Question 8.
How can we change the priority and what levels of priority are provided by .NET?
Answer:
Thread Priority can be changed by using

Thread name.Priority = ThreadPriority.Highest

Following are different levels of Priority provided by .NET:

  • ThreadPriority.Highest
  • ThreadPriority.above normal
  • ThreadPriority.Normal
  • ThreadPriority.below normal
  • ThreadPriority.Lowest

Question 9.
What does the AddressOf operator do in the background?
Answer:
The AddressOf operator creates a delegate object to the Background Process method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the start () method of the thread.

Question 10.
How can you reference the current thread of the method?
Answer:
“Thread. CurrentThread” refers to the current thread running in the method. “CurrentThread” is public static property.

Question 11.
What is Thread.Sleep ( ) in threading?
Answer:
Thread’s execution can be paused by calling the Thread. sleep method. This method takes an integer value that determines how long the thread should sleep. For example, Thread.CurrentThread. Sleep(2000).

Question 12.
How can we make a thread sleep for the infinite period?
Answer:
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread. Sleep (System.Threading.Timeout. Infinite). To interrupt this sleep you can call the Thread. Interrupt method.

Question 13.
What is Suspend and Resume in Threading?
Answer:
It is similar to Sleep and Interrupt Suspend allows you to block a thread until another Thread calls Thread. Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

Note: In threading interviews, most people get confused with Sleep and Suspend. They look very similar.

Question 14.
What is the way to stop a long-running thread?
Answer:
Thread. Abort ( ) stops the thread execution at that moment itself.

Question 15.
How do I debug the thread?
Answer:
This window is only seen when the program is running in debug mode. In windows, one of the Windows is “Threads” (See Figure 17.1).

Threading Interview Questions in .NET chpter 17 img 1

Question 16.
What is Thread. Join ( ) in threading?
Answer:
There are two versions of Thread join-

  • Thread, join ( ).
  • Thread. join (Integer) returns a Boolean value.

The Thread. join method is useful for determining if a thread has been completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise, it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done.

For example, you have “Thread1” and “Thread2” and while executing ‘Thread1″ you call “Thread2 .Join ( ) “.So “Thread1” will wait until “Thread2” has completed its execution and again invoke “Thread1”.

Thread. Join (Integer) ensures that threads do not wait for a long time. If it exceeds a specific time, which is provided in integer the waiting thread will start.

Question 17.
What are Daemon threads and how can a thread be created as Daemon?
Answer:
Daemon thread’s run in the background and stops automatically the program is not running. An example of a Daemon thread is ‘Garbage collector’. The garbage collector runs until some .NET code is running or else it is idle.
You can make a thread Daemon by

Thread, Isbackground-true

Question 18.
How is shared data managed in threading?
Answer:
There are certain situations that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you’ll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time, you will have a deadlock problem. To avoid dead lock we need to use the ‘ SyncLock’ keyword as shown in the code snippet below.

SyncLock x
         'Do something with x 
End SyncLock

Question 19.
Can we use events with threading?
Answer:
Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.

Question 20.
How can we know a state of a thread?
Answer:
“Threadstate” property can be used to get the detail of a thread. Thread can have one or a combination of status. ‘System.Threading.Threadstate’ enumeration has all the values to detect a state of the thread. Some sample states are running, isAlive, suspended, etc.

Question 21.
What is the use of interlocked class?
Answer:
The interlocked class provides methods by which you can achieve the following functionalities:

  • Increment Values
  • Decrement values
  • Exchange values between variables
  • Compare values from any thread. in a synchronization mode Example: System.Threading.Interlocked.Increment(IntA)

Question 22.
What is a monitor object?
Answer:
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor objects.

Question 23.
What are wait handles?
Answer:
Wait handles send signals of a thread status from one thread to another thread. There is three kinds of wait modes:

  • WaitOne
  • WaitAny
  • WaitAII

When a thread wants to release a Wait handle it can call the set method. You can use Mutex (mutually exclusive) objects to avail for the following modes. Mutex objects are synchronization objects that can only be owned by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource.

The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to be signaled and the next waiting thread gets ownership

Question 24.
What is ManualResetEvent and AutoResetEvent?
Answer:
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signal using Set, but they automatically return to non signaled as soon as a waiting thread is notified that the event became signaled.

Question 25.
What is Reader-Writer Locks?
Answer:
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows non-exclusive access when reading the resource. Reader-Writer locks are a good alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.

Question 26.
How can you avoid deadlock in threading?
Answer:
Good and careful planning can avoid deadlocks. There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to another thread, and using ThreadState property you can poll and act accordingly.

Question 27.
What is TPL (Task Parallel Library)?
Answer:
TPL stands for Task Parallel Library. It’s introduced in .NET 4.0 framework to simplify threading.TPL is a set of APIs (Application Programming Interface) that sits on top of core threading and simplifies threading. When we use threading API directly you need to take care of pooling, ensure that the thread executes on multiple processors, data and task parallelism, etc. When you use TPL all these things are taken care of so that you concentrate on the work rather than these lower-level technical details.
TPL simplifies the following things from development aspect:

  • Thread pooling is taken care of internally.
  • TPL ensures that threads will execute on multiple processors.
  • Cancellation of threads made easier.
  • State management is simplified as compared to core threading.

All components of TPL (task parallel library) exist in the below namespace.

using System. Threading. Tasks;

To invoke a thread using TPL we need to use the below syntax. We need to create the object of task object to invoke a thread.

Task tsk = new Task(MyTask); // Run the task. 
tsk.Start( );

Question 28.
What is the difference between thread and process?
Answer:
A thread is a path of execution that runs on a CPU (Central Processing Unit), a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always runs in a process context.

Note: Its difficult to cover threading interview question in this small chapter. These questions can take only 
to a basic level. If you are attending interviews where people are looking for threading specialist, try to get 
deeper in to synchronization issues, as that is the important point they will stress.