Monday 2 January 2012

Threading

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.
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.
What is a Thread?
A thread is the basic unit to which the operating system allocates processor time.
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 is used for 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.
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. 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 :-
1. ThreadPriority.Highest
2. ThreadPriority.AboveNormal
3. ThreadPriority.Normal
4. ThreadPriority.BelowNormal
5. ThreadPriority.Lowest
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
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'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).
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.
What the way to stop a long running thread?
Thread.Abort() stops the thread execution at that moment itself.
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.
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.
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 before accessing it. However, if the two threads lock the same variable at the same time, you'll have a deadlock problem.
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. 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 :-
1. Increment Values.
2. Decrement values.
3. Exchange values between variables.
4. Compare values from any thread. in a synchronization mode.
Example - System.Threading.Interlocked.Increment(IntA)
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.
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 :-
1. WaitOne.
2. WaitAny.
3. 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.
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 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.
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.
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.


No comments:

Post a Comment