Threading – DOT NET Chapter Wise Interview Questions
What is multi-tasking?
It is a feature of modern operating systems with which we can run multiple programs at same time, for example Word, Excel, etc.
What is multi-threading?
Multi-threading forms subset of multi-tasking. Instead of having to switch between programs, this feature switches between different parts of the same program.
What is a thread?
A thread is the basic unit to which the operating system allocates processor time.
Did VB6 support multi-threading?
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.
Can we have multiple threads in one App domain?
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.
Which namespace has threading?
‘Systems.Threading’ has all the classes related to implement threading. Any .NET application which cam 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.
Can you explain in brief how can we implement threading?
Private Sub Forml_Load (ByVal sender As System. Object, ByVal e as
System.EventArgs) Handles MyBase.Load
Dim pthreadl As New Thread (AddressOf Threadl)
Dim pthread2 As New Thread (AddressOf Thread2)
Public Sub Threadl ()
Dim pint count As Integer
Dim pstr As String
Pstr - "This is first thread"
Do Until pint count > 5
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
Pint count = pint count + 1
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.
How can we change priority and what the levels of priority are provided by .NET?
Thread Priority can be changed by using
Threadname.Priority = ThreadPriority.Highest
Following are different levels of Priority provided by .NET:
What does AddressOf operator do in background?
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.
How can you reference current thread of the method?
“Thread. CurrentThread” refers to the current thread running in the method. “CurrentThread” is a public static property.
What is Thread.Sleep () in threading?
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).
How can we make a thread sleep for infinite period?
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.
What is Suspend and Resume in Threading?
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.
What the way to stop a long running thread?
Thread. Abort () stops the thread execution at that moment itself.
How do I debug thread?
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).
What is Thread.Join () in threading?
There are two versions of Thread join-
- join () .
- join (Integer) this returns a Boolean value.
The Thread.join method is useful for determining if a thread has 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.
Example you have ‘ThreadT’ and “Thread2” and while executing ‘Thread1 you call “Thread2 .Join () “.So “Thread1’ will wait until “Thread2” has completed its execution and the 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.
What are Daemon threads and how can a thread be created as Daemon?
Daemon thread’s run in background and stops automatically the program is not running. Example of a Daemon thread is ‘Garbage collector’. Garbage collector runs until some .NET code is running or else it is idle.
You can make a thread Daemon by
How is shared data managed in threading?
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.
'Do something with x
Can we use events with threading?
Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.
How can we know a state of a thread?
“Threadstate” property can be used to get 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 thread. Some sample states are isrunning, isAlive, suspended etc.
What is use of interlocked class?
Interlocked class provides methods by which you can achieve following functionalities:
- Increment Values
- Decrement values
- Exchange values between variables
- Compare values from any thread.in a synchronization mode
What is a monitor object?
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.
What are wait handles?
Wait handles sends signals of a thread status from one thread to other thread. There are three kind of wait modes:
When a thread wants to release a Wait handle it can call 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
What is ManualResetEvent and AutoResetEvent?
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 signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.
What is Reader Writer Locks?
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.
How can you avoid deadlock in threading?
A 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 other threadand using Threadstate property you can poll and act accordingly.
What is TPL (Task Parallel Library)?
TPL stands for Task Parallel Library. Its introduced in .NET 4.0 framework to simplify threading.TPL is set of APIs (Application Programming Interface) which sits on top of core threading and simplifies threading. When we use threading API directly you need to take care of pooling, ensure that 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 internally.
- TPL ensures that threads will execute on multiple processors.
- Cancellation of threads made easier.
- State management simplified as compared to core threading.
All components of TPL (task parallel library) exists 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.
What is the difference between thread and process?
A thread is a path of execution that run on 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 run 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.