CLR and .NET Framework
The CLR is the runtime for executing managed code. C# is one of several managed
languages that get compiled into managed code. Managed code is packaged into an
assembly, in the form of either an executable file (an .exe) or a library (a .dll), along
with type information, or metadata.
Managed code is represented in Intermediate Language or IL. When the CLR loads
an assembly, it converts the IL into the native code of the machine, such as x86. This
conversion is done by the CLR’s JIT (Just-In-Time) compiler. An assembly retains
almost all of the original source language constructs, which makes it easy to inspect
and even generate code dynamically.
The CLR performs as a host for numerous runtime services. Examples of these services
include memory management, the loading of libraries, and security services.
The CLR is language-neutral, allowing developers to build applications in multiple
languages (e.g., C#, Visual Basic .NET, Managed C++, Delphi.NET, Chrome .NET,
and J#).
How the Garbage Collector Works:
The GC begins with its root object references, and walks the object graph, marking
all the objects it touches as reachable. Once this process is complete, all objects that
have not been marked are considered unused, and are subject to garbage collection.
Unused objects without finalizers are immediately discarded; unused objects with
finalizers are enqueued for processing on the finalizer thread after the GC is complete.
These objects then become eligible for collection in the next GC for the object’s
generation (unless resurrected).
The remaining “live” objects are then shifted to the start of the heap (compacted),
freeing space for more objects. This compaction serves two purposes: it avoids
memory fragmentation, and it allows the GC to employ a very simple strategy when
allocating new objects, which is to always allocate memory at the end of the heap.
This avoids the potentially time-consuming task of maintaining a list of free memory
segments.
If there is insufficient space to allocate memory for a new object after garbage
collection, and the operating system is unable to grant further memory, an
OutOfMemoryException is thrown.
Generational collection
The most important optimization is that the GC is generational. This takes advantage
of the fact that although many objects are allocated and discarded rapidly, certain
objects are long-lived and thus don’t need to be traced during every collection.
Basically, the GC divides the managed heap into three generations. Objects that have
just been allocated are in Gen0 and objects that have survived one collection cycle
are in Gen1; all other objects are in Gen2.
The large object heap
The GC uses a separate heap called the Large Object Heap (LOH) for objects larger
than a certain threshold (currently 85,000 bytes). This avoids excessive Gen0
collections—without the LOH, allocating a series of 16 MB objects might trigger a
Gen0 collection after every allocation.
The LOH is not subject to compaction, because moving large blocks of memory
during garbage collection would be prohibitively expensive. This has two
consequences:
1. Allocations can be slower
2. The LOH is subject to fragmentation
The large object heap is also nongenerational: all objects are treated as Gen2.
Concurrent and background collection
The GC must freeze (block) your execution threads for periods during a collection.
This includes the entire period during which a Gen0 or Gen1 collection takes place.
The GC makes a special attempt, though, at allowing threads to run during a Gen2
collection
Forcing Garbage Collection (not recommend)
GC.Collect()
A good guideline is to implement IDisposable yourself if any field in your class is assigned an object that implements IDisposable. (Such as System.Timers.Timer)(System.Threading.Timer is different)
Monitor the memory leaks: long memoryUsed = GC.GetTotalMemory (true);
Occasionally, it’s useful to hold a reference to an object that’s “invisible” to the GC
in terms of keeping the object alive. This is called a weak reference, and is implemented
by the System.WeakReference class.
One use for WeakReference is to cache large object graphs.
http://www.shafqatahmed.com/2008/01/weakreference-b.html
Asynchronous Methods
asynchronous programming model or APM
An asynchronous method aims never to block any thread, instead using a pattern of
returning with a callback.
The end goal of the APM is thread economy.
The purpose of asynchronous methods isn’t to
provide a convenient mechanism for executing a method in parallel with the caller;
it’s to optimize thread resources.
Here’s the golden rule of the APM: Make good use of the CPU, or exit with a callback!
The primary use for asynchronous methods is handling many potentially longrunning
concurrent requests—typically over slow network connections.
IAsyncResult BeginXXX (in/ref-args, AsyncCallback callback, object state);
return-type EndXXX (out/ref-args, IAsyncResult asyncResult);
public delegate void AsyncCallback (IAsyncResult ar);
To avoid blocking, you will nearly always call the EndXXX method from inside the
callback method. Callbacks always run on pooled threads.
http://en.csharp-online.net/CSharp_Delegates_and_Events%E2%80%94Asynchronous_method_calls
http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx
Collections
ICollection Properties
IComparer
Copmare method
IEqualityComparer
GetHashCode, Equals
SortedList calss is a dictionary.
Race conditions and deadlocks
http://support.microsoft.com/kb/317723
A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.
A deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked.