Chapter 3: Threading
- What is multi-tasking?
It is a feature of modern operating systems with which we can run multiple programs at same time
- 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.
- 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.
- Can we have multiple threads in one AppDomain ?
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. All threading classes are defined in System.Threading namespace.
- Which namespace contains threading – related classes ?
Systems.Threading has all the classes related to implement threading. Any .NET application who wants to implement threading has to import this namespace. .NET program always has at least two threads running one is the main program and second is the garbage collector.
- How can we implement threading ?
Below is an example in VB.Net:
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)
Public Sub Thread1()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is first thread”
Do Until pintcount > 5
pintcount = pintcount + 1
Public Sub Thread2()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is second thread”
Do Until pintcount > 5
pintcount = pintcount + 1
- 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 :
- 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.
10. 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.
11. What does Thread.Sleep() do in threading?
Thread’s execution can be paused by calling the Thread.Sleep method. This method takes an integer value in milliseconds that determines how long the thread should sleep. Example: Thread.CurrentThread.Sleep(2000).
12. 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.
13. What are Suspend() and Resume() methods in threading?
Those are 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.
14. How to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
15. How to debug threads ?
“DebugWindowsTreads” in Visual Studio gives an access to the threads debug window.This window is only seen when the program is running in debug mode.
16. What is Thread.Join() in threading?
There are two versions of 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.
17. 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 a daemon by assigning Thread.IsBackground=true
18. When working with shared data in threading how do you implement synchronization ?
There are certain situtations 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.
‘Do something with x
19. Can we use events with threading?
Yes, we can use events with thread; this is one of the techniques to synchronize one thread with other.
20. 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.
21. What is Interlocked class?
Interlocked class provides methods by which you can achieve following functionalities in a synchronization mode:
- Increment Values.
- Decrement values.
- Exchange values between variables.
- Compare values from any thread.
Example : System.Threading.Interlocked.Increment(intVal)
22. 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.
23. What are Wait handles and 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.
24. What are 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.
25. What is ReaderWriter Lock?
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.
26. 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.
27. 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.
Chapter 4: Remoting and Webservices
Chapter 5: Caching Concepts