Monday, September 10, 2012

Struct in C#.NET

            //NOTES: STRUCT

            // - struct is a value type 
            // - no need to use new keyword
            // - cannot inherit from struct(error: cannot derive from sealed type)
            // - struct allows properties/method which uses reference type.



namespace StructSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p;
            p.x = 10;
            p.y = 20;

            p.name = "wgi";

            Console.WriteLine(p.Add());

            Console.Read();
        }
    }


    struct Point
    {
        public int x, y;

        public string name;

        public int Add() { return x + y; }
    }


    //class newPoint : Point
    //{
    //}
}

E-Book Gallery for Microsoft Technologies

Monday, April 16, 2012

Advantage of abstract class over interface

Advantage of abstract class over interface:

Consider versioning:

·         You cannot add members to interface without breaking the existing code.  
·         But you can safely add new members to abstract classes.



Choosing between interface & abstract class:

·         Use interface when you want to implement multiple inheritance.
·         Use interface for decoupling
·         Use abstract class in case of frequent versioning scenario.

Compare 2 generic list

How to Compare 2 generic lists:

            List<int> list1 = new List<int> { 1, 2, 3, 5, 6 };
            List<int> list2= new List<int> { 1, 2, 3 };


Answer: if you are trying to see if 2 sets are equal, then the best approach is to check the except extension method on Enumerable class. And make sure that the result does not have any entries.


            var except = Enumerable.Except(list1, list2);

            if (except.Count() > 0)
                Console.Write("Not equal");
            else
                Console.Write("equal");;

Reference:

Tuesday, February 28, 2012

Multithreading in C# - Basics

·         Multithreading – is the parallel execution of code
·         Use of multithreading
1. Maintaining a responsive UI
2. Allow requests to process simultaneously

·         Join –wait for the thread to end/complete the execution
·         Sleep – pauses the current thread for specified period
·         IsAlive – property returns true if thread is alive

Note: Thread will be in blocked state while waiting on a join/sleep. And will not consume resources

·         Yeild – pauses thread running on same processor.
·         Preempted – a thread is said to be preempted when its execution is interrupted due to external factor
·         Interrupt and abort – interrupt will wait for until thread block to complete, while abort breaks where it is executing

·         Thread scheduler manages multithreading
1. It’s a function typically CLR delegates to Operating System
2. TS ensures all active threads are allocated appropriate execution time
3. And threads are waiting/blocked do not consume CPU resource
4. On  a Single processor system, TS perform time-slicing
5. On a multi processor system, TS perform mixture of time slicing and concurrency

·         Process Vs Thread – a thread in execution is a process. Threads run parallel within a single process. Processes are fully isolated from each other, where threads are partially isolated from each other. (threads share heap memory with other threads)

·         Foreground and background threads – by default foreground threads are created. (Thread.IsBackground=true)

·         Thread Priority – property determines how much execution time it gets (Lowest, BelowNormal, Normal, AboveNormal, Highest)

·         Thread pooling –allow execution of the threads simultaneously.   Once the limit is reached it queues up and continues execution when other finishes (ThreadPool.QueueUserWorkItem)

·         Asynchronous delegate – If a thread wants to notify (return value back) after it has finished execution, then this can be achieved using asynchronous delegate.

1. Create a delegate for the method to be called (Func delegate)
2. Call BeginInvoke on delegate with IAsyncResult return value
Note: BeginInvoke return immediately to the caller.

·         ThreadState: gives you threads execution status.
o   Unstarted
o   Running
o   WaitSleepJoin
o   Stopped

·         Thread synchronization
o   Lock (Monitor.Enter, Monitor.Exit)
o   Mutex
o   Semaphore
o   SemaphoreSlim
o   SpinLock

·         Lock – ensure only one thread can enter particular section of code at a time (Exclusive lock)
object locker = new object();
                 System.Threading.Monitor.Enter(locker);

           
                 System.Threading.Monitor.Exit(locker);
·         Mutex – is an exclusive lock. Purpose is inter-process synchronization. It can work across multiple processes. Mutex can be computer-wide or application-wide.

·         Semaphore – Ensures not more than a specified number of concurrent threads can access a resource. It is cross process. 


Multithreading (computer architecture)

Multithreading (computer architecture)

 

Multithreading aims to increase utilization of a single core by using thread-level as well as instruction-level parallelism

 

Instruction-level parallelism (ILP) is a measure of how many of the operations in a computer program can be performed simultaneously.

1. e = a + b

2. f = c + d

3. g = e * f

Operation 3 depends on the results of operations 1 and 2, so it cannot be calculated until both of them are completed. However, operations 1 and 2 do not depend on any other operation, so they can be calculated simultaneously.

 

Advantage of multithreading:

·         concurrent execution : advantage of a multithreaded program allows it to operate faster on computer systems

·         One main use of multithreading, for single-CPU systems, is the ability for an application to remain responsive to input.

 

Drawback of multithreading:

·         Careless use of threading can cause deadlock. If two threads are accessing same resource at same time can cause deadlock.

Operating systems schedule threads in one of two ways:

1.       Preemptive multithreading is generally considered the superior approach, as it allows the operating system to determine when a context switch should occur.

2.       Cooperative multithreading, on the other hand, relies on the threads themselves to relinquish control once they are at a stopping point

 

Reference:

http://en.wikipedia.org/wiki/Multithreading_(computer_architecture)

http://en.wikipedia.org/wiki/Instruction_level_parallelism




DISCLAIMER:
This email (including any attachments) is intended for the sole use of the intended recipient/s and may contain material that is CONFIDENTIAL AND PRIVATE COMPANY INFORMATION. Any review or reliance by others or copying or distribution or forwarding of any or all of the contents in this message is STRICTLY PROHIBITED. If you are not the intended recipient, please contact the sender by email and delete all copies; your cooperation in this regard is appreciated.