Sunday, 1 January 2012

DotNet Frequently Asked Questions on Threading - 2

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 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.

SyncLock x


'Do something with x


End SyncLock



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.

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.

No comments:

Post a Comment