#57 Synchronization Constructs-Thread

Thread Synchronization Constructs can be performed in two ways 

1.User Mode Constructs-They utilize Hardware(Cpu Instruction to make thread safe),no interruption of OS.(Volatile,InterLocked,SpinLock).

 

2.Kernel Mode Constructs -Operating System takes care of thread synchronizations,and the os provide certain mechanism to handle thread safe block.(WaitHandle,Semaphore,Mutex)

A block  operation by thread in User Mode  is called LiveLock(Usage of CPU Forever). A block operation by thread in Kernel mode is called DeadLock(Wastage of Memory) 

#56 Critical Sections-Threads

Critical Section: Critical Section is a piece of code or a shared resource that  must not be accessed concurrently by different threads.

Problems(If CS is not handled):

1.Race Condition.

2.DeadLock

Mechanism to handle Critical Section:

1.Atomic Updates

2.Partitioning

3.Wait-Based Synchronization Protocol. 

#55: When should you throw exception ?

When you make an Assumption of function and it it violates the assumption ,then you might probably need to throw an exception. For instance,Let’s assume that we have function which returns true if the length of List is greater than 50 and false if it is less than 50.Now what if the list is Null?(function Doe not have assumption ) ,this creates the necessary to throw exception  

//This functions assume that you past list item filled with inetgers.
//It is not assumed that list might be null,so here you need to throw exception
private static bool ValidateListLength(List<int>l)
 {
 try
 {
 return l.Count>50;
 }
 catch 
 {
 throw ;
 }
 return false;
 }

#54: Invoking Explicit Interface-Cannot Invoke with Class Instance,but requires Interface Instance

You cannot Invoke Explicit Interface with Class Instance,You require Interface Instance to call the Explicit Interface

 class Sample:ITest
 {
 //Interface Defined Explicitly
 void ITest.Test()
 {
 Console.WriteLine("Hello");
 }
 }

To Invoke the explicit interface,you need Interface Instance,not the class instance

/*You cannot invoke Explicit Interface with Class Instance but the 
 Interface instance. ITest is the inetrface instance
 */
 ITest s1 = new Sample();
 s1.Test();

#53 Mutiple Interface with Same Contract

Let’s Assume we have two interface with same contract:

interface ITest
 {
 void Test(); //Same Contract as of other interface
 }
interface ITest1
 {
 void Test(); //Same Contract as of other interface
 }

To define both the Interface with same contract  in a class,you have to define Interface Explicitly without Access Modifier.

class Sample:ITest,ITest1
 {
 void ITest.Test()
 {
 Console.WriteLine("Hello");
 }
 void ITest1.Test()
 {
 Console.WriteLine("Hello1");
 }
 } 

To invoke the specific Contract,

//You cannot invoke Explicit Interface with Class Instance.
 ITest s1 = new Sample();
 s1.Test();
 ITest1 s2 = new Sample();
 s2.Test();