Managed Vs Unmanaged Threads (CLR Thread vs Windows Threads)

Managed threads are created by CLR. As of now there is one -one mapping in between CLR thread and windows thread but in future this may change and CLR may introduce logical threading. In order to access windows thread we need to directly call WIn32 APIs via PInvoke that should be avoided as much as possible.

Dedicated Threads Vs Thread Pool Vs Timer

                                 Dedicated Thread 
 Thread Pool
 Timer
 Tasks
 When to use
For long running task or mission critical task that can not be canceled in between.
For unimportant tasks such as cleanup.
when request processing requests are being revived such as responding to HTTP request. 
When you do not want to track the output of job running , fire and forgot strategy
 When need to use periodic task such as triggering a file download or refreshing UI from a remote data location
 When need a thread pool like solution but also need to check status while task is running.
 Performance  Cost 
 High Low , as pool and thread creation is optimized by CLR
 very low
 Low

When to Use Background Worker Thread

When we need to know the progress of any background operation. It has built in support progress update

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.

When to use Thread Pool

  1. Always prefer using a ThreadPool thread. It is efficient and helps avoid the overhead associated with creating, starting, and stopping threads. Avoid using the ThreadPool if...
  2. the task runs for the lifetime of your application,
  3. you need the thread to be a foreground thread,
  4. you need to manipulate the thread priority, or
  5. you need the thread to have a fixed identity (aborting, suspending, discovering).

Background worker Vs Thread Pool

  • Both in background creates thread but difference is there uses scenario listed below
  •  Your program does batch processing  >>Consider ThreadPool
  • Your program makes many (3+) threads >>Consider ThreadPool
  • Your program uses Windows Forms >>Consider BackgroundWorker
  • You need one extra thread >>Use BackgroundWorker
  • You have many short-lived threads >>ThreadPool
  • Thread Pool Mostly used in Server application while Background Worker is mostly used in WinForms  http://www.dotnetperls.com/threadpool

Limitations of Thread Pool

  1. All threads are created in normal mode priority change not supported
  2. All threads are background thread
  3. Abort is not supported
  4. No Call back mechanism supported

User Mode Scheduling (UMS) VsFiber 

UMS threads differ from fibers in that each UMS thread has its own thread context instead of sharing the thread context of a single thread.

When to suppress execution context flow.

Execution context is a data structure that is passed from parent to child thread and it have significant overhead, by suppressing context overflow we can gain performance in server application, however we should do only when if code that will be executed by thread is not using any such information that execution context provide such as uername of access rights. 

Live Lock Vs Dead Lock

If the system is in dead-lock and only user mode construct are used the it is called live lock because user mode locks are implemented using spin wait that burn CPU cycle white. The same situation will be called Dead-Lock if kernel mode constructs are used because they do not waste CPU cycle.

Kernel Vs User Mode Synchronization 

User Mode : Light weight but burn CPU cycle, Kernel mode: Expensive to create but saved CPU cycles and Context Switching  

What is the purpose of “ Control.InvokeRequired”

Because controls are always owned by the UI thread, it is generally unsafe to make calls to controls from a different thread. You can use the Control.InvokeRequired property to determine if it is safe to make a call to a control from another thread. If Invoke-Required returns False, it is safe to make the call to the control. If InvokeRequired returns True, however, you should use the Control.Invoke method on the owning form to supply a delegate to a method to access the control. Using Control.Invoke allows the control to be accessed in a thread-safe manner.

When to use thread Pool

Always prefer using a ThreadPool thread. It is efficient and helps avoid the overhead associated with creating, starting, and stopping threads. Avoid using the ThreadPool if...

  • task runs for the lifetime of your application,
  •  you need the thread to be a foreground thread,
  •  you need to manipulate the thread priority, or
  • you need the thread to have a fixed identity (aborting, suspending, discovering).

When to explicitly use thread class

Use the Thread class for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.http://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread

What is default size of dot net thread pool

25 per processor, 1024 on Windows 7

List the possible use of threads in developing a thick client server application.

  • Managing incoming connection
  • Asynchronous  data retrieval
  • Auto suggest
  • Interactive Server site validation
  •  Managing outgoing message queue etc.

Background worker Vs Thread Pool

  1. Both in background creates thread but difference is there uses scenario listed below
  2.  Your program does batch processing  >>Consider ThreadPool
  3. Your program makes many (3+) threads >>Consider ThreadPool
  4.  Your program uses Windows Forms >>Consider BackgroundWorker
  5.  You need one extra thread >>Use BackgroundWorker
  6.  You have many short-lived threads >>ThreadPool
  7.  Thread Pool Mostly used in Server application while Background Worker is mostly used in WinForms  http://www.dotnetperls.com/threadpool

How to know that the progress of operation running under thread pool?

Thread pool itself do not provide any such construct so we need to use Asynchronous Programming Model.

How to periodically call an asynchronous operation?

Best way is to use Threading.Timer Class that actually pushes the task in to application thread pool.

Limitations of Thread Pool

  1.  All threads are created in normal mode priority change not supported
  2. All threads are background thread
  3. Abort is not supported
  4. No Call back mechanism supported

UnsafeQueueUserWorkitem Vs QueueUserWorkitem

  1. UnsafeQueueUserWorkitem : Do not Honor CAS and have security threat but performance is high , usually not recommended
  2. QueueUserWorkitem : Honor CAS but low in performance

What is the purpose of Thread.Interrupt ?

  1. It is replacement of Resume () and works in a different mechanism than resume.
  2. You can interrupt a waiting thread by calling Thread.Interrupt on the blocked thread to throw a ThreadInterruptedException, which breaks the thread out of the blocking call. The thread should catch the ThreadInterruptedException and do whatever is appropriate to continue working. If the thread ignores the exception, the runtime catches the exception and stops the thread.
  3. If the target thread is not blocked when Thread.Interrupt is called, the thread is not interrupted until it blocks. If the thread never blocks, it could complete without ever being interrupted.
  4. If a wait is a managed wait, then Thread.Interrupt and Thread.Abort both wake the thread immediately. If a wait is an unmanaged wait (for example, a platform invoke call to the Win32 WaitForSingleObject function), neither Thread.Interrupt nor Thread.Abort can take control of the thread until it returns to or calls into managed code. In managed code, the behavior is as follows:
  5.  Thread.Interrupt wakes a thread out of any wait it might be in and causes a ThreadInterruptedException to be thrown in the destination thread.

What is the Solution to cache coherency problem

Use Volatile R/W or volatile keyword.

What are the limitations of Interlocked Methods?

They are very few in numbers and work only on Int32.

 Monitor Vs Lock Statements

Lock implicitly implements Monitor.Enter and Monitor.Leave

What is the best Implementation while using lock statement?

Always use private locking object. 

 What is ReaderWriterLock

It defines a lock that supports single writers and multiple readers.  http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx

When to Use Kernel Locking Construct
  •   When we need inter process synchronization
  •   Thread have a long wait as a part of synchronization, because Monitor is a Spin-wait implementation that waste CPU Cycle while Kernel object do not waste CPU cycle .

How does recursion impact synchronization mechanism

A recursive lock is a variant on the mutex lock. A recursive lock allows a single thread to acquire the lock multiple times before releasing it. Other threads remain blocked until the owner of the lock releases the lock the same number of times it acquired it. Recursive locks are used during recursive iterations primarily but may also be used in cases where multiple methods each need to acquire the lock separately.

Locks that support recursion such as

ReaderWriterLock and Monitor do not support this programming architecture.

Manual Vs Auto Reset Event

  • Manual reset Event: Allow multiple threads to enter and some thread need to reset it.
  • Auto Reset Event: It is more like Mutex and automatically got reset ASAP a thread acquire it.

Event Vs Mutex

  • Technically Mutex is a Binary semaphore
  • Practically speaking the functional difference between an Event and a Mutex is that, an event is generally used in situations where one thread performs some initialization work, and then signals other threads to perform rest of the work. objects
  • On the other hand, a mutex is generally used when we need to safeguard a common resource against simultaneous read/write operations from multiple threads. Hence the concept of ownership by a thread. The thread which ows the mutex (which means the threadID field of the mutex structure is set to the threadId of the calling thread) has exclusive rights to read/write on the common resource, while other thread wait for bieng scheduled.

Live Lock Vs Dead Lock

When thread are blocked at CRL Synchronization Construct then it is called Live Lock and on the other hand when it is blocked on kernel synchronization construct them it is called dead lock.

What is wait handle?

  • It represents 32 Bit Integer value of kernel synchronization objects.
  • This class is typically used as a base class for synchronization objects. Classes derived from WaitHandle define a signaling mechanism to indicate taking or releasing access to a shared resource, but use the inherited WaitHandle methods to block while waiting for access to shared resources.
  • Use the static methods of this class to block a thread until one or more synchronization objects receive a signal.

Does Lock Keyword work on value type

No because lock actually uses sync block that re implemented by heap only. Also it is not really required because value types are always passed by copying so multiple threads have different copies of same value object.

Comments