Monday, April 28, 2008

DOTNET FAQ-4

3. Threading

(B)What is Multi-tasking ?
It’s a feature of modern operating systems with which we can run multiple programs at
same time example Word, Excel etc.
(B)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. Example
you are writing in word and at the same time word is doing a spell check in background.
(B)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(B)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a freethreading
model, which allows multiple threads to run against the same set of data.
(B)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.
(B)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading. Any .NET application
who wants to implement threading has to import this namespace.
Note :- .NET program always has at least two threads running one is the main program
and second is the garbage collector.
(I)Can you explain in brief how can we implement threading ?
3. Threading
143
Private Sub Form1_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 Thread1()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is first thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Public Sub Thread2()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is second thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Above is a sample code which shows simple sample code for threading. Above sample
code can be found in “Threading” folder in CD provided. Above sample has two methods
“Thread1()” and “Thread2()” which are started in multi-threaded mode in Form load
event of the sample.
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.
(A)How can we change priority and what the levels of priority are
provided by .NET ?
144
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.
In the sample provided look out for code where the second thread is ran with a high
priority.
Following are different levels of Priority provided by .NET :-
√ ThreadPriority.Highest
√ ThreadPriority.AboveNormal
√ ThreadPriority.Normal
√ ThreadPriority.BelowNormal
√ ThreadPriority.Lowest
(A)What does AddressOf operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess 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
(A)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.
(I) What's 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. Example
Thread.CurrentThread.Sleep(2000).
(A)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.
(A) What is Suspend and Resume in Threading ?
145
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.
(A)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
(A) How do I debug thread ?
Figure :- 3.1 Debug thread window
This window is only seen when the program is running in debug mode. In windows one of
the window is “Threads”.
146
(A)What is Thread.Join() in threading ?
There are two versions of Thread.Join :-
√ Thread.join().
√ Thread.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 "Thread1" 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.
(A)What are Daemon threads and how can a thread be created as
Daemon?
Daemon thread's run in background and stop automatically when nothing is running
program. Example of a Daemon thread is "Garbage collector". Garbage collector runs
until some .NET code is running or else its idle.
You can make a thread Daemon by
Thread.Isbackground=true
(A) When working with shared data in threading how do you implement
synchronization ?
There are certain somethings 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
147
before accessing it. However, if the two threads lock the same variable at the same time,
you'll have a deadlock problem.
SyncLock x
'Do something with x
End SyncLock
(I)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.
(A)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.
(A) 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.
Example :- System.Threading.Interlocked.Increment(IntA)
(A) 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.
SyncLock and End SyncLock statements are provided in order to simplify access to monitor
object.
148
(A) What are wait handles ?
Twist :- What is a mutex object ?
Wait handles sends signals of a thread status from one thread to other thread. There are
three kind of wait modes :-
√ WaitOne.
√ WaitAny.
√ WaitAll.
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
(A) 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.
(A) What is ReaderWriter 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 nonexclusive access when reading the resource. ReaderWriter locks are a useful
alternative to exclusive locks that cause other threads to wait, even when those threads
do not need to update data.
(I) 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 thread, ThreadState property which you
can poll and act accordingly etc.
(B) What is the difference between thread and process?
A thread is a path of execution that run on CPU, 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's the
important point they will stress.

No comments: