Problematic windows updates

wusa.exe /uninstall /kb:2859537
wusa.exe /uninstall /kb:2872339
wusa.exe /uninstall /kb:2882822


Book read roadmap


Csharp 5.0 in a Nutshell book summary

@ helps to avoid name conflicts with predefined names

implicit cast happens when compiler can garanty that no information will be lost and cast always sucessful, otherwise it will be explicit cast

params keyword allows to set multiple params for function

multidimentional arrays: rectangular, jagged

optional parameters cannot be ref or out

extern keyword can create name for libraries referenced

global namespace

struct could not have user defined parameterless constructor

object initializers {property=value}

properties get set can have different accessibility level

indexers implements operator[]


readonly modifier prevents a field from being modified after construction. A read-only field can be assigned only in its declaration or within the enclosing type’s constructor.

const fields are static are evaluated at compile time it is better than static readonly field but require recompilation for client assembly also it is like cpp defines

static constructors are parameterless and are called before class instantiating or static fields accessing

static classes are restricted to hold only static members

partial classes splitted for several files

partial methods splitted for declaration and implementation

as operator downcasts, but doesnt throw an exception in case cast is invalid but returns a null

is operator checks whether specific cast can be successfully processd

virtual methods, properties, events, indexers should be specified by virtual keyword at base class and override within inherited class

new member modificator is used to remove warning that says that same class member was redifined menas hide at subclass

sealed keyword marks some overriden method to prevent it overriding in futher subclasses, if we have whole class selaed this means all virtual methods are sealed

base keyword is like this keyword but refers base class

field initialization happens from subclass to base class order, but constructes are called from base to sub class order

overloading resolution happens on static objects type at comple time, until dynamic keyword is used, in this case resolution is postponed to runtime and will be done regarding to actual objects type

structs are value types, not support inheritance (besides implicit inheritance from system.valuetype), dosnt have parameterless constructors, finalizer and virtual members

structs constructor should initialize all fields, or parameterless biultin constructor initialize it by zeroing, class member initialization while declaration is not allowed.

Class accessibility overrides members accessibility

Methods access modifiers should remain the same while inheriting, class access modifier should be the same or more restrictive

interface can declare methods, properties, indexers, events

interface elements are public and could not be marked by other modifier

interface is implemented without virtual or abstract keyword is sealed

Accessing struct via interface causes boxing

Flag attribute for enum allows to use it as masked object, pow of two


Nested types

1. Access the enclosing type and everything that enclosing type can access

2. Can be declared with all possible access modifiers, default is private

3. Accessing of nested components requires type qualification.




Generic classes

public class Stack<T>


int position;

T[] data = new T[100];

public void Push (T obj) { data[position++] = obj; }

public T Pop() { return data[–position]; }


where T – type parameter

Stack<int> stack = new Stack<int>()


Stack<T> is an open type

Stack<int> is a closed type


Generic methods

static void Swap<T> (ref T a, ref T b)




int x = 5; int y = 10;

Swap (ref x, ref y); or Swap<int> (ref x, ref y);


List of generic parameters can be overloaded with different number of parameters.


default() – keyword is used to get a default value of generic parameter


Properties, indexers, events, fields, constructors, operators cannot declare type parameters.

Classes, structs, interfaces, delegates and methods can declare type parameters.


Typeof operator – Type a1 = typeof (A<>); // Open (unbound) type during runtime for reflection purposes.


Generic Constraints

where T : <some base-class> // Base-class constraint

where T : <some interface>  // Interface constraint

where T : class // Reference-type constraint

where T : struct // Value-type constraint (excludes Nullable types)

where T : new() // Parameterless constructor constraint

where U : T // Naked type constraint


Subclassing Generic Types

Subclass can leave the base class’s type parameters open, as in the following example:

class Stack<T> {…}

class SpecialStack<T> : Stack<T> {…}

Subclass can close the generic type parameters with a concrete type:

class IntStack : Stack<int> {…}

Subtype can also introduce fresh type arguments:

class List<T> {…}

class KeyedList<T,TKey> : List<T> {…}


Self referencing generic declarations

public interface IEquatable<T> { bool Equals (T obj); }

public class Balloon : IEquatable<Balloon>

{ … }


Static Data

Static data is unique for each closed type:


Cast operator can perform

– Numeric conversion

– Reference conversion

– Boxing/unboxing conversion

– Custom conversion (via operator overloading;


as operator cannot perform custom conversions



public interface IPoppable<out T> { T Pop(); }

IPoppable<string> s = …;

IPoppable<object> b = s;

Template interface are covariant with out (<out T>) keyword

Template classes are not covariant

Arrays are covariant


Out types at template interfaces IPoppable<out T> – defines that this parameter is used only as return type of methods declared via this interface.



public interface IPushable<in T> { void Push (T obj); }

IPushable<object> b = …;

IPushable<string> s = b;

Template interface are contravariant with in(<in T>) keyword – when generic parameter appears at input positions.


Delegate defines a type, the instance of this type can refer some function. It is immutable.


MultiCast delegates – can call group of methods, in the same order as methods were added to group (by +=, -=, but it creates new instance).

If there are return values within methods of multicast delegates – caller obtain the last delegate call result.


Instance method delegate – should be supplied (by assigning to <delegate instance field>.Target) with reference to object instance which is used to call method.


Delegate can have generic type


Delegate Compatibility

Delegate types are all incompatible with each other, even if their signatures are the

same, but D2 d2 = new D2 (d1);

Delegates are equal in case the refer the same method.


Delegate Parameter compatibility (contravariance)

Delegate type can have more concrete parameter that function that will be pointed by delegate instance. It is for parameters and return value.


Generic delegates

The same as generic interface



Language entity that implements an idea of broadcaster and subscribers.

Broadcaster call an event like a function.

Can be fired only from a class that declare it.

Event can be only += (added) or -= (deleted) with some new subscriber, but could not be assigned. It prevent overriding other already subscribed recipients.

Event can be an interface member, delegate is not.


System.EventArgs – superclass for all arguments passed into delegate.


Three rules for Framework compatible delegate:

– It must have a void return type.

– It must accept two arguments: the first of type object, and the second a subclass of EventArgs. The first argument indicates the event broadcaster, and the second argument contains the extra information to convey.

– Its name must end with EventHandler.


Event Accessors – += ad -=

Compiler defines default, but it is possible to redefine it by custom implementation.


Events can be virtual, overridden, abstract, or sealed,  static.



Unnamed method converted into delegate or expression tree by compiler

(parameters) => expression-or-statement-block

Lambda statement can capture outer variables (captured variables), such lambda is called closure.

Captured variables are evaluated while calling not while capturing.

Lifetime of any variable capture by lambda is extended to corresponding delegate.

Local variable instantiated within labda is instantiated each call for this lambda.


Capturing iteration variables: compiler makes the iteration variable declared within loop, so while calling delegate variable will have the last loop value. To have several different iteration variables captured, you need to assign iteration variable to local variable and then capture the local variable.


Anonymous methods – ancestor of lambda, obsolete.


try-catch-finally keywords

Try must be followed by catch block or finally or both. Catch executes if error occurs, finally executes at any case after try or catch block.



… // exception may get thrown within execution of this block


catch (ExceptionA ex)


… // handle exception of type ExceptionA


catch (ExceptionB ex)


… // handle exception of type ExceptionB




… // cleanup code



Exception handling is quite expensive.

Catch param should be Exception type or its subtype.

Only on catch block is executed for one exception

Catch(…) is used for C++ exceptions that might be not inherited from Exception, in this case it is wrapped by CLR by RuntimeWrappedException.


Finally executes after:

– catch block finishes

– try block is left by jump, goto or return

– try block ends.


using keyword – call Dispose method (System.IDisposable) to clear resources.


Throw and rethrow exception by throw [ex] keyword. In case of different exception rethrow, InnerException property should be set to aid debugging.


Key properties of System.Exception: StackTrace, Message and InnerException.


Pattern TryXXX method (example: Parse and TryParse).


Enumerator is a read-only, forward-only cursor over a sequence of values.

It implements System.Collections.IEnumerator or System.Collections.Generic.IEnumerator<T>


Enumerable object (could be passed to foreach):

– Implements IEnumerable or IEnumerable<T>

– Has a method named GetEnumerator that returns an enumerator


Collection initializers

List<int> list = new List<int> {1, 2, 3};


Iterator is a method, property, or indexer that contains one or more yield statements.

Iterator must return one of the following four interfaces:

– System.Collections.IEnumerable

– System.Collections.Generic.IEnumerable<T>

– System.Collections.IEnumerator

– System.Collections.Generic.IEnumerator<T>


Types of yields:

yield return <return value>;

yield break;


Iterator can get an another iterator as an input parameter.


Nullable types

It is possibility to assign a null value to value-type items.

Example: int? i = null;

Internally such types are wrapped by class, that has a method “HasValue” that shows whether real value was assigned.


Operator lifting for nullable types – means using operators from wrapped types.


?? Null Coalescing Operator

int y = x ?? 5; – means: If the operand is non-null, give it to me; otherwise, give me a default value.


Operation overloading


Operators that can be overloaded

+ (unary); − (unary); !; ˜; ++; −−; +; −; *; /; %; &; |; ^; <<; >>; ==; !;=; >; <; >=; <=;


– Implicit and explicit conversions (with the implicit and explicit keywords)

– true and false

– compound “+=” are overridden by “+”, “||” by “|”


An operator is overloaded by declaring an operator function. An operator function

has the following rules:

– The name of the function is specified with the operator keyword followed by

an operator symbol.

– The operator function must be marked static and public.

– The parameters of the operator function represent the operands.

– The return type of an operator function represents the result of an expression.

– At least one of the operands must be the type in which the operator function is



Extension methods


Extension methods allow an existing type to be extended with new methods without altering the definition of the original type. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.


For example:

public static class StringHelper


public static bool IsCapitalized (this string s)


if (string.IsNullOrEmpty(s)) return false;

return char.IsUpper (s[0]);




Interfaces can be extended too.


Extension method chain

public static class StringHelper


public static string Pluralize (this string s) {…}

public static string Capitalize (this string s) {…}



string x = “sausage”.Pluralize().Capitalize();


Instance method will always take precedence over an extension method.

In case of two extension methods the more specific method takes precedence.


Anonymous Types


var dude = new { Name = “Bob”, Age = 23 };


int Age = 23;

var dude = new { Name = “Bob”, Age, Age.ToString().Length };

is equivalent to:

var dude = new { Name = “Bob”, Age = Age, Length = Age.ToString().Length };


Comparison between two anonymous types is implemented comparison between members.


Array of anonymous types instancies

var dudes = new[]


new { Name = “Bob”, Age = 30 },

new { Name = “Tom”, Age = 40 }



Dynamic Binding


Static binding – method is found by following sequence:

Duck d = …



– method named Quack on Duck.

– method named Quack with optional parameters on Duck.

– methods on base classes of Duck

– extension methods that take Duck as its first parameter


Dynamic Binding – method is found in runtime in same sequence as while static binding (if not found RuntimeBinderException is thrown)

dynamic d = GetSomeObject();



Custom Binding – When dynamic object implements IDynamicMetaObjectProvider (IDMOP), that interface is used to perform the binding.


COM interop binding


Deep equivalence between the dynamic and object types.


var and dynamic are different, since var is checked on compile time.

Fields, properties, methods, events, constructors, indexers, operators, and conversions can all be called dynamically.


Effect of dynamic type information is cascading:

dynamic x = 2;

var y = x * 3; // Static type of y is dynamic


Dynamic method can be used for method overloading for methods that have statically bound values.


Functions that could not be called dynamically:

– Extension methods (via extension method syntax)

– Members of an interface, if you need to cast to that interface to do so

– Base members hidden by a subclass




Attributes are an extensible mechanism for adding custom information to code elements (assemblies, types, members, return values, parameters, and generic type parameters). This extensibility is useful for services that integrate deeply into the type system, without requiring special keywords or constructs in the C# language.


Attribute is a class that inherits System.Attribute.


Attributes may have parameters: named and positioned

[XmlElement (“Customer”, Namespace=”;)]

public class CustomerEntity { … }


By default, the target of an attribute is the code element it immediately precedes,

which is typically a type or type member, but assembly is also can be affected by attributes.



Several attributes can be specified within same brackets separated by coma or by several separate lines.


Caller Info Attributes

The attributes can mark method’s default parameters to assign the values about caller. It is syntax sugar.

[CallerMemberName] applies the caller’s member name

[CallerFilePath] applies the path to caller’s source code file

[CallerLineNumber] applies the line number in caller’s source code file


Unsafe Code and Pointers (mostly for value type)

C# supports direct memory manipulation via pointers within blocks of code marked

unsafe and compiled with the /unsafe compiler option. Pointer types are primarily

useful for interoperability with C APIs, but may also be used for accessing memory

outside the managed heap or for performance-critical hotspots.


The fixed Statement

Within fixed fixed block it is possible to get a pointer on any value type, array of value types or string and in scope of block this object will not be shifted  in memory.

fixed (int* p = &test.x) // Pins test


*p = 9;



stackalloc – allocates some memory on stack

int* a = stackalloc int [10];


fixed keyword allows create fixed size arrays at structs

unsafe struct UnsafeUnicodeString


public short Length;

public fixed byte Buffer[30]; // Allocate block of 30 bytes



void * is the same as at C++


Preprocessor defines

#if #elif #endif (with || ! && operations) – like C++


Conditional attributes


public class TestAttribute : Attribute {} – Test attribute will be used within another source files only if DEBUG will be declared within this source file.


#pragma warning – like C++


XML Documentation – three slashes ///, two start stars /** */

Standard documentation tags are <summary>, <remarks>, <param>, <returns>, <exception>, <permission>, <example>, <code or c>, <see>, <seealso>, <paramref>, <list>, <para>, <include>.




char – alias for System.Char and represents single unicode character

System.Char defines a range of static methods to manipulate with characters.


string (== System.String) is an immutable (unchangeable) sequence of characters.

string can be foreach-ed


Ordinal string comparison: interprets character as a number

Culture-sensitive string comparison: interpret characters with reference to a particular alphabet


String equality comparison

string’s == operator (or of string.Equals method) always performs ordinal casesensitive comparison.

string’s CompareTo instance method performs culture-sensitive, case-sensitive order



The StringBuilder class (System.Text namespace) represents a mutable (editable) string.


Text encoding maps characters from their numeric code point to a binary representation.


Dates and Times are represented by three immutable structs:

TimeSpan – count of 100ns intervals

DateTime and DateTimeOffset – handle data and time, differs in handling timezones.


Format Providers – handles format strings and different locale formatting details(like ‘.’ and ‘,’ in float number) in scope of formatting and parsing tasks: format strings, number styles, date-time format strings, date-time styles.


Convert.ToInt32 – makes banker’s rounding


XmlConverting – convert into XML compatible strings


TypeConverting – convert some string into some class/struct instance, like Color from “Black”


BitConverter – converts into sequence of bits


Internationalisation can be tested by setting some specific culture for thread.

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo (“tr-TR”);


BigInteger – represents an arbitrarily large integer without any loss of precision


Complex – representing complex numbers with real and imaginary components of type



Random class generates a pseudorandom sequence of random bytes, integers, or



Enums can be casted into enums, string of int.

Enum.GetValues – enumerating enum’s values.


Tuples – set of differently typed elements




public interface IEnumerator


bool MoveNext();

object Current { get; }

void Reset();



public interface IEnumerable


IEnumerator GetEnumerator();



public interface ICollection<T> : IEnumerable<T>, IEnumerable


int Count { get; }

bool Contains (T item);

void CopyTo (T[] array, int arrayIndex);

bool IsReadOnly { get; }

void Add(T item);

bool Remove (T item);

void Clear();



public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable


T this [int index] { get; set; }

int IndexOf (T item);

void Insert (int index, T item);

void RemoveAt (int index);



public interface IReadOnlyList<out T> : IEnumerable<T>, IEnumerable


int Count { get; }

T this[int index] { get; }





ConstrainedCopy performs an atomic operation: if all of the requested elements cannot

be successfully copied (due to a type error, for instance), the operation is rolled



List<T> and ArrayList – work by maintaining an internal array of objects, replaced with a larger array upon reaching capacity.


LinkedList<T> – is a generic doubly linked


Queue<T> and Queue are first-in first-out (FIFO) data structures, methods: Enqueue, Dequeue, Peek.


Stack<T> and Stack are last-in first-out (LIFO) data structures, methods: Push, Pop and Peek.


BitArray is a dynamically sized collection of compacted bool values. It is more memory-efficient than both a simple array of bool and a generic List of bool, because it uses only one bit for each value, whereas the bool type otherwise occupies one byte for each value.


HashSet<T> and SortedSet<T>


• Their Contains methods execute quickly using a hash-based lookup.

• They do not store duplicate elements and silently ignore requests to add


• You cannot access an element by position.


Dictionaries are collection in which each element is a key/value pair.

In Big-O notation, retrieval time by key is:

O(1) for Hashtable, Dictionary, and OrderedDictionary

O(log n) for SortedDictionary and SortedList

O(n) for ListDictionary (and nondictionary types such as List<T>)


Hashtable (non generic) – is nongeneric Dictionary


OrderedDictionary (non generic) is a nongeneric dictionary that maintains elements in the same order that they were added. With an OrderedDictionary, you can access elements both by index and by key.


ListDictionary (non generic) uses a singly linked list to store the data. Its efficiency with very small lists (fewer than 10 items).


HybridDictionary (non generic) is a ListDictionary (non generic) that automatically converts to a Hashtable upon reaching a certain size.


SortedDictionary<,> (red/black tree based) is much faster than SortedList<,> at inserting elements in a random sequence.


SortedList<,> is implemented internally with an ordered array pair, fast retrieval (via a binary-chop search) but poor insertion performance. It has an extra ability: to access items by index as well as by key.


ReadOnlyCollection<T> is a wrapper, or proxy, that provides a read-only view of a collection.


– A type for which Equals and GetHashCode return meaningful results can be used as a key in a Dictionary or Hashtable.

– A type that implements IComparable /IComparable<T> can be used as a key in any of the sorted dictionaries or lists.


public interface IEqualityComparer<T>


bool Equals (T x, T y);

int GetHashCode (T obj);


public interface IComparer <in T>


int Compare(T x, T y);



For structs:

public interface IStructuralEquatable


bool Equals (object other, IEqualityComparer comparer);

int GetHashCode (IEqualityComparer comparer);


public interface IStructuralComparable


int CompareTo (object other, IComparer comparer);





LINQ enables you to query any collection implementing IEnumerable<T>.

Implemented as extension method on collection



public static IEnumerable<TSource> Where<TSource>

(this IEnumerable<TSource> source, Func<TSource,bool> predicate)

public static IEnumerable<TSource> OrderBy<TSource,TKey>

(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)

public static IEnumerable<TResult> Select<TSource,TResult>

(this IEnumerable<TSource> source, Func<TSource,TResult> selector)


Some lambdas can change the type of each element.


Query expressions always start with a from clause and end with either a select or group clause.


Range variable n appears in every clause in the query. And yet, the variable actually enumerates over a different sequence with each clause.


Deferred execution – means that query is executed when it is enumerated, not when constructed.


Reevaluation – means that query executed each time when it is enumerated.


Capturing variables – variable is captured, but read and used while query execution.


Constructing LINQ query – constructing decorator, that will be executed while iterating decorator. Multiple queries – multiple nested decorators.


Subqueries – when query is a part of lambda-expression within another query. Each quey is scoped so it is possible to use the same named query-variable.


Composition Strategies for building more complex queries:

Progressive query construction – simply two different queries one after another.

IEnumerable<string> query = from n in names select n.Replace (“a”, “”);

query = from n in query where n.Length > 2 orderby n select n;


Using the into keyword

IEnumerable<string> query = from n in names select n.Replace (“a”, “”)

into noVowel where noVowel.Length > 2 orderby noVowel select noVowel;

– Wrapping queries

IEnumerable<string> query =

from n1 in


from n2 in names select n2.Replace (“a”, “”)


where n1.Length > 2 orderby n1 select n1;


Projection Strategies

Object Initializers – it is possible to initialize set of objects with result of query

class TempProjectionItem


public string Original; // Original name

public string Vowelless; // Vowel-stripped name



string[] names = { “Tom”, “Dick”, “Harry”, “Mary”, “Jay” };

IEnumerable<TempProjectionItem> temp = from n in names select

new TempProjectionItem


Original = n,

Vowelless = n.Replace (“a”, “”)



Anonymous Types – it is possible to do the same without class declaration

var intermediate = from n in names select new


Original = n,

Vowelless = n.Replace (“a”, “”)


IEnumerable<string> query = from item in intermediate where item.Vowelless.Length > 2

select item.Original;

Variable of temp type should be declared as var.

Or the same with into keyword


var query = from n in names select new


Original = n,

Vowelless = n.Replace (“a”, “”)


into temp where temp.Vowelless.Length > 2 select temp.Original;


The let Keyword – introduces a new variable alongside the range variable.


IEnumerable<string> query = from n in names

let vowelless = n.Replace (“a”, “”)

where vowelless.Length > 2 orderby vowelless select n;


Interpreted Queries – for remote datasource.

They operate over sequences that implement IQueryable<T>, and they resolve to the query operators in the Queryable class, which emit expression trees that are interpreted at runtime.


There are two IQueryable<T> implementations in the .NET Framework:


– Entity Framework (EF)


It’s also possible to generate an IQueryable<T> wrapper around an ordinary enumerable

collection by calling the AsQueryable method.


Combining Interpreted and Local Queries

A query can include both interpreted and local operators. A typical pattern is to have the local operators on the outside and the interpreted components on the inside; in other words, the interpreted queries feed the local queries.


Interpreted queries, which use Queryable operators, take expression trees.

We can see this by comparing the signature of the Where operator in Enumerable and Queryable:

public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate)

public static IQueryable<TSource> Where<TSource> (this IQueryable<TSource> source, Expression<Func<TSource,bool>> predicate)


The standard query operators fall into three categories:

– Sequence in, sequence out (sequence-to-sequence)

– Sequence in, single element or scalar value out

– Nothing in, sequence out (generation methods)


Sequence to Sequence

Accepting one or more sequences as input and emitting a single output sequence.



IEnumerable<TSource> to IEnumerable<TSource>

Returns a subset of the original elements.

Where, Take, TakeWhile, Skip, SkipWhile, Distinct



IEnumerable<TSource> →IEnumerable<TResult>

Transforms each element with a lambda function.

Select, SelectMany



IEnumerable<TOuter>, IEnumerable<TInner>→ IEnumerable<TResult>

Meshes elements of one sequence with another.



IEnumerable<TSource> →IOrderedEnumerable<TSource>

Returns a reordering of a sequence.

OrderBy, ThenBy, Reverse



IEnumerable<TSource> →IEnumerable<IGrouping<TSource,TElement>>

Groups a sequence into subsequences.



– Set operators

IEnumerable<TSource>, IEnumerable<TSource>→ IEnumerable<TSource>

Takes two same-typed sequences and returns their commonality, sum, or difference.

Concat, Union, Intersect, Except


– Conversion methods: Import


OfType, Cast


– Conversion methods: Export

IEnumerable<TSource> →An array, list, dictionary, lookup, or sequence

ToArray, ToList, ToDictionary, ToLookup, AsEnumerable, AsQueryable


Sequence→Element or Value

The following query operators accept an input sequence and emit a single element or value.


– Element operators

IEnumerable<TSource> →TSource

Picks a single element from a sequence.

First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, ElementAt, ElementAtOrDefault, DefaultIfEmpty


– Aggregation methods

IEnumerable<TSource> →scalar

Performs a computation across a sequence, returning a scalar value (typically a number).

Aggregate, Average, Count, LongCount, Sum, Max, Min


– Quantifiers

IEnumerable<TSource> →bool

An aggregation returning true or false.



In the third and final category are query operators that produce an output sequence

from scratch.

– Generation methods


Manufactures a simple sequence.

Empty, Range, Repeat


Filtering IEnumerable<TSource>→ IEnumerable<TSource>


Where – returns a subset of elements that satisfy a given condition

Take – returns the first count elements and discards the rest

Skip – ignores the first count elements and returns the rest

TakeWhile – emits elements from the input sequence until the predicate is false

SkipWhile – ignores elements from the input sequence until the predicate is false, and then emits the rest

Distinct – returns a sequence that excludes duplicates


Projecting IEnumerable<TSource>→ IEnumerable<TResult>


SelectMany – lambda expression must emit a child sequence per input element. The final result

is a concatenation of the child sequences emitted for each input element.


SelectMany is supported in query syntax and is invoked by having an additional generator in other words, an extra from clause in the query.




Join – applies a lookup strategy to match elements from two collections, emitting a flat result set

GroupJoin – as above, but emits a hierarchical result set

Zip – enumerates two sequences in step (like a zipper), applying a function over each element pair


Query syntax

from outer-var in outer-enumerable

join inner-var in inner-enumerable on outer-key-expr equals inner-key-expr [ into identifier ]


Ordering IEnumerable<TSource>→ IOrderedEnumerable<TSource>


OrderBy, ThenBy – sorts a sequence in ascending order

OrderByDescending, ThenByDescending – sorts a sequence in descending order

Reverse – returns a sequence in reverse order


Syntax :

names.OrderBy (s => s.Length).ThenBy (s => s[1]).ThenBy (s => s[0]);


from s in names orderby s.Length, s[1], s[0] select s;


Grouping IEnumerable<TSource>→ IEnumerable<IGrouping<TSource,TElement>>


GroupBy – groups a sequence into subsequences


Set Operators IEnumerable<TSource>, IEnumerable<TSource>→IEnumerable<TSource>


Concat – returns a concatenation of elements in each of the two sequences

Union – returns a concatenation of elements in each of the two sequences, excluding duplicates

Intersect – returns elements present in both sequences

Except – returns elements present in the first, but not the second sequence


Conversion Methods


OfType – converts IEnumerable to IEnumerable<T>, discarding wrongly typed elements

Cast – converts IEnumerable to IEnumerable<T>, throwing an exception if there are any wrongly

typed elements

ToArray – converts IEnumerable<T> to T[]

ToList – converts IEnumerable<T> to List<T>

ToDictionary – converts IEnumerable<T> to Dictionary<TKey,TValue>

ToLookup – converts IEnumerable<T> to ILookup<TKey,TElement>

AsEnumerable – downcasts to IEnumerable<T>

AsQueryable – casts or converts to IQueryable<T>


Element Operators IEnumerable<TSource>→ TSource


First, FirstOrDefault – returns the first element in the sequence, optionally satisfying a predicate

Last, LastOrDefault  – returns the last element in the sequence, optionally satisfying a predicate

Single, SingleOrDefault – equivalent to First/First OrDefault, but throws an exception if there is more than one match

ElementAt, ElementAtOrDefault – returns the element at the specified position

DefaultIfEmpty – returns a single-element sequence whose value is default(TSource) if the sequence has no elements


Aggregation Methods IEnumerable<TSource>→ scalar


Count, LongCount – returns the number of elements in the input sequence, optionally satisfying a predicate

Min, Max – returns the smallest or largest element in the sequence

Sum, Average – calculates a numeric sum or average over elements in the sequence

Aggregate – performs a custom aggregation


Quantifiers IEnumerable<TSource>→ bool


Contains – returns true if the input sequence contains the given element

Any – returns true if any elements satisfy the given predicate

All  – returns true if all elements satisfy the given predicate

SequenceEqual – returns true if the second sequence has identical elements to the input sequence


Generation Methods void→IEnumerable<TResult>


Empty – creates an empty sequence

Repeat – creates a sequence of repeating elements

Range – creates a sequence of integers


<customer id=”123″>


<lastname>Bloggs<!–nice name–></lastname>



XElement lastName = new XElement (“lastname”, “Bloggs”);

lastName.Add (new XComment (“nice name”));

XElement customer = new XElement (“customer”);

customer.Add (new XAttribute (“id”, 123));

customer.Add (new XElement (“firstname”, “Joe”));

customer.Add (lastName);


XElement customer =

new XElement (“customer”, new XAttribute (“id”, 123),

new XElement (“firstname”, “joe”),

new XElement (“lastname”, “bloggs”,

new XComment (“nice name”)




Disposal and Garbage collection


IDisposable interface


public interface IDisposable


void Dispose();



using statement provides a syntactic shortcut for calling Dispose on objects that implement IDisposable, using a try/finally block. For example:


using (FileStream fs = new FileStream (“myFile.txt”, FileMode.Open))


// … Write to the file …



The compiler converts this to:


FileStream fs = new FileStream (“myFile.txt”, FileMode.Open);



// … Write to the file …




if (fs != null) ((IDisposable)fs).Dispose();



Disposal rules:

1. Disposed object could not be called (exception).

2. Dispose() method could not be called twice (exception).

3. Disposed object should call dispose for all its disposable members.


A root is something that keeps an object alive. If an object is not directly or indirectly referenced by a root, it will be eligible for garbage collection.

A root is one of the following:

– A local variable or parameter in an executing method (or in any method in its call stack)

– A static variable

– An object on the queue that stores objects ready for finalization


Finalizers (destructor)

Prior to an object being released from memory, its finalizer runs, if it has one. A finalizer is declared like a constructor, but it is prefixed by the ˜ symbol:

class Test




// Finalizer logic…




Finalizer cannot be declared as public or static, cannot have parameters, and cannot call the base class.


Here are some guidelines for implementing finalizers:

– Ensure that your finalizer executes quickly.

– Never block in your finalizer (Chapter 14).

– Don’t reference other finalizable objects.

– Don’t throw exceptions.



Suppose a finalizer modifies a living object such that it refers back to the dying object (someone will refer it while object finalization called). When the next garbage collection happens (for the object’s generation), the CLR will see the previously dying object as no longer orphaned—and so it will evade garbage collection.


A resurrected object’s finalizer will not run a second time – unless you call GC.ReRegisterForFinalize.


GC performance optimization techniques:

1. Generational collection

2. Large object heap (LOH)

3. Background collection for Gen2

4. GC notifications


GC.AddMemoryPressure and GC.RemoveMemoryPressure – tell to CLR about unmanaged memory used to optimize.


Weak References – not tracked by CLR.

var sb = new StringBuilder (“this is a test”);

var weak = new WeakReference (sb);




Preprocessor directives – conditional compilation, conditional attributes (some class method can be marked by conditional attribute, and all calls to this method will be skipped in case attribute is not defined)


Debug and Trace Classes – all methods of the Debug class are defined with [Conditional(“DEBUG”)] or [Conditional(“TRACE”)]. Both define methods: Fail (shows dialog) and Assert. There is listener that listen debug and trace events, by default there is only one.


Code contract

Contract.Requires (list != null); // Precondition

Contract.Ensures (list.Contains (item)); // Postcondition

ccrewrite.exe tool should be invoked with app with contracts, it replace some contract instructions into right place.



All functions that you call from arguments passed to contract methods (Requires, Assumes, Assert, etc.) must be pure, means they must not alter the values of fields. Purity set be attribute.


public static bool IsValidUri (string uri) { … }

It is possible to specify what exception will be thrown in case contract is broken and and scope of code block that is guarded by contract.


Contracts on Interfaces and Abstract Methods – can attach conditions to interface members and abstract methods. The binary rewriter then automatically weaves these conditions into the members’ concrete implementations.


Debugger Integration

DbgCLR is Visual Studio stripped of everything but the debugger, and it is a free download with the .NET Framework SDK. It requires that you download the whole SDK.


There is static debugger class, it is possible attach, navigate and explore program execution.


Windows Event Logs – it is possible write, read and monitor it.


Performance Counters – it is possible to work with Windows performance counters.


Stopwatch class – for measuring execution times.




Thread can execute, sleep, join to another thread and wait (on lock for example).


Lock – instruction that allows to guard some block of code only fo one single thread execution (like CS)


lock (<any referenceable object instance>)


//only one thread here



try-catch for getting thread exception should be located inside a thread that executes, but on in thread which starts it.


In WPF, Metro, and Windows Forms applications, you can subscribe to “global” exception handling events, Application.DispatcherUnhandledException and Application.ThreadException.


Foreground threads – threads created by default, app wait for all foreground threads to be terminated before exiting.


Background threads – are shutted down when application is closed (even finally blocks are not executed).


Thread Priority – enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest }


Process priority


Signaling – some thread wait until it gets notification from another thread.


UI controls can be accessed directly only from thread that created it, otherwise marshaling is required.


Thread Pool – set of threads (no waste time for creating new threads):

– cannot set the Name of a pooled thread, making debugging more difficult

– pooled threads are always background threads.

– blocking pooled threads can degrade performance

Disadvantage of thread pool – it is not easy to get some information from pooled thread and unable to get notification about thread finishing (it should be joined)


Tasks – represents a concurrent short operation that may or may not be backed by a thread

Task.Run (() => Console.WriteLine (“Foo”));


TaskCreationOptions.LongRunning option to request a non-pooled thread


task.Wait() – blocks calling thread until task is complete.


For long time operation –

Task task = Task.Factory.StartNew (() => …, TaskCreationOptions.LongRunning);


Task returning values

Task<int> task = Task.Run (() => { Console.WriteLine (“Foo”); return 3; });

int result = task.Result; – if task is not finished, this blocks the current thread.


Task Exceptions are passed to waiting thread


It is possible subscribe to unobserved exceptions at a global level via the static event TaskScheduler.UnobservedTaskException. to catch all exception from all threads.


Continuation says to a task, “when you’ve finished, continue by doing something else.” – callback that executes once upon completion of an operation.


var awaiter = task.GetAwaiter();

awaiter.OnCompleted (<lambda here>);


task.ContinueWith (<lambda here>);


Lambda can call int result = awaiter.GetResult(); to get result or an exception in case exception happened while task execution.



Allows you to create a manually driven task




Transformed from

var result = await expression;



Transformed to

var awaiter = expression.GetAwaiter();

awaiter.OnCompleted (() =>


var result = awaiter.GetResult();




Methods with the async modifier are called asynchronous functions, because they themselves are typically asynchronous.


await expression can appear in place of any expression (within an asynchronous function) except for inside a catch or finally block, lock expression, unsafe context or an executable’s entry point (main method).


Unnamed lambda also can be async.


Exception thrown after await instruction by default is posted besides sync context of current thread and can crush the program (unless it caught by general exception handler).


Optimisation for async:

1. Completing synchrony – we can cache all results within a async function and check that perhaps result is already evaluated and can be returned immediately.




Async patterns


1. Cancellation – cancellation token passed to most async functions and can be configured outside to stop function execution.


2. Progress reporting – callback object is used to provide feedback about progress of task.


3. Task-based Asynchronous Pattern (TAP) – set of obligations for some methods to be true async: return a hot task, have “Async” suffix, accept cancellation and progress tracking objects, return result quickly, do not hold thread in case I/O.

4. Task CombinatorsWhenAny (returned first finished task), WhenAll (returned array of results of all tasks), it possible to write own combinators.


Obsolete Async Patterns (chronologically)

1. Asynchronous Programming Model (APM) – oldest one.- BeginXXX + EndXXX methods that bound by token.

2. Event-Based Asynchronous Pattern (EAP) – event is called when async operation is completed.

3. BackgroundWorker – class that allows to specify async operation and callback on complete and method Run that starts worker.


Streams and I/O


1. Backing store – stream itself like FileStream or NetworkStream

2. Decorator – streams that changes data somehow (crypto or zipping) on the fly

3. Adapter – wraps the stream and provides methods to deals with it, like ReadLine over text reader.


The abstract Stream class is the base for all streams, it allows: read, write, seek, close/flush, timeout and other operations.


Async reading/writing – ReadAsync/WriteAsync


1. Backing store streams: FileStream, MemoryStream, NetworkStream, PipeStream (Named and anonymous), IsolatedStorageFileStream, BufferedStream

2. Decorator –  DeflateStream and GZipStream – two zipping algorithms.

3. Adapters – Text, Stream, String, Binary, XML – reads and writers.


Catching Filesystem Events – can track file system’s operations

Memory mapped files – transport data between processes



Client-Side Classes: WebRequest and WebResponse, WebClient, HttpClient, WebProxy

Server-Side Classes: HttpListener




Serialization mechanisms


– The data contract serializer – new (version tolerance, preserves object’s references)

– The binary serializer – old for Remouting (except in the Metro profile)

– The (attribute-based) XML serializer – old for SOAP(XmlSerializer)

– The IXmlSerializable interface (implementing own serializer)


Data Contract Serializer types:

– DataContractSerializer (Loosely couples .NET types)

– NetDataContractSerializer (Tightly couples .NET types)

Attributes for markup

namespace SerialTest


[DataContract] public class Person


[DataMember] public string Name;

[DataMember] public int Age;




Subclasses and referenced objects are serialized as well.


The NetDataContractSerializer always preserves referential equality. The DataCon tractSerializer does not, unless you specifically ask it to. This means that if the same object is referenced in two different places, a DataCon tractSerializer ordinarily writes it twice.


Version Tolerance

By default missed fields is not a problem, but [DataMember (IsRequired=true)] – makes an exception in case of missed field.


Null and Empty Values – (just missed or specified) behaviour defined by [DataMember (EmitDefaultValue=false)] attribute.


Collections are handled as well.


It is possible to specify a hook-delegate the called before/after serialization/deserialization by specifying an attribute on some method: [OnSerializing], [OnSerialized], [OnDeserializing], [OnDeserialized].


The Binary Serializer – for remoting and disk saving, is not available in Metro.

[Serializable] public sealed class Person


public string Name;

public int Age;



The Serializable attribute is not inherited

With automatic properties, the binary serialization engine serializes the underlying compiler-generated field. The name of this field, unfortunately, can change when its type is recompiled, breaking compatibility with existing serialized data. The workaround is either to avoid automatic properties


Formatters for serialization:BinaryFormatter and SoapFormatter


Binary Serialization Attributes

[NonSerialized] – marks the fields that should ot be serialized (that can be dynamically calculated for instance)

[OnDeserializing], [OnDeserialized], [OnSerializing],  [OnSerialized] – callbacks

[OptionalField] – allows adding field between serialization and deserialization


Implementing ISerializable gives a type complete control over its binary serialization

and deserialization (means GetObjectData method is called while ser and deser)


XML Serialization

It is two ways to use it – mark fields with some attributes or implement IXmlSerializable, by default (without any marks) – it serializes all public fields and properties on a type.


[XmlIgnore] – marks do not serialize some field

[XmlAttribute] – marks that some field will be serialized as XML attribute, not a field

[XmlElement (“<some name>”)] – allows that some field will have another name at XML file

[XmlElement (Order = 2)] – changes an order of elements at XML-file

[XmlInclude (typeof (<sub-class name>))] – marks some class that its subclasses will be serialized as well.

Child object fields a recursively serialized as well.

Collection are serialized as well.

Limitations: cannot add serialization hooks nor serialize nonpublic members

IXmlSerializable (ReadXml, WriteXml) – for total control




A WinRT library has a .winmd extension and is similar to a .dll, except that it contains only metadata and no IL code.


An assembly contains four kinds of things:

– An assembly manifest (mandatory) – Provides information to the .NET runtime, such as the assembly’s name, version, requested permissions, and other assemblies that it references

– An application manifest – Provides information to the operating system, such as how the assembly should be deployed and whether administrative elevation is required

– Compiled types – The compiled IL code and metadata of the types defined within the assembly

– Resources – Other data embedded within the assembly, such as images and localizable text


The assembly manifest serves two purposes:

• It describes the assembly to the managed hosting environment.

• It acts as a directory to the modules, types, and resources in the assembly.


Multifile assemblies have to be compiled from the command line


The Assembly class in System.Reflection is a gateway to accessing assembly metadata

at runtime


A strongly named assembly has a unique and untamperable identity. It works by adding two bits of metadata to the manifest:

– A unique number that belongs to the authors of the assembly

– A signed hash of the assembly, proving that the unique number holder produced the assembly


A delay-signed assembly is flagged with the correct public key, but not signed with the private key. A delay-signed assembly is equivalent to a tampered assembly and would normally be rejected by the CLR. The developer, however, instructs the CLR to bypass validation for the delay-sign assemblies on that computer, allowing the unsigned assemblies to run. When it comes time for final deployment, the private key holder re-signs the assembly with the real key pair.


Authenticode is a code-signing system whose purpose is to prove the identity of the publisher. Published certificates are used. Authenticode and strong-name signing are independent: you can sign an assembly with either or both systems. It is not only for managed binaries – for native as well.


Global Assembly Cache – for assemblies in the GAC, versioning is centralized at the machine

level and controlled by the computer’s administrator. For assemblies outside the

GAC, versioning is handled on an application basis, so each application looks after

its own dependency and update issues (typically by maintaining its own copy of each

assembly that it references).


GAC disadv:

– admin privileges for installation are required

– GAC modules are prefered over local

– GAC modules are used by multiple app – so the broken binary will affect all of them


Installing assembly at GAC: gacutil /i MyAssembly.dll

Uninstalling assembly at GAC: gacutil /u MyAssembly


Installing a new version of assembly – does not remove the previous one – both are kept by GAC (uninstall+install can be used as workaround).


Resources: for binary data or for something that should be localized.

Resources can be embedded directly or through .resource file


.resource file – for potentially localizable content (it can be explored by specific API). It is binary files are built over .resx human readable files (XML based)


Satellite assembly (cannot contain executable code) – assembly with localized .resource file, main assembly contains default .resource. Framework check the current OS’s culture and tries to load corresponding satellite assembly.


Cultures (en, de) and subcultures (en-AU, de-AT)

CurrentCulture reflects the regional settings of the Windows control panel, whereas

CurrentUICulture reflects the language of the operating system.

Regional settings – timezone and format of currency and dates.

CurrentCulture determines the default behavior of such functions as DateTime.Parse.

CurrentUICulture determines the language in which the computer communicates with the user.

ResourceManager, by default, uses the current thread’s CurrentUICulture property to determine the correct satellite assembly to load.


Resolving Assemblies

First The CLR checks whether assembly is already loaded from probing path of as AssemblyResolve event result and return it, next –  first checks the GAC, then the probing paths (generally the application base directory), and as a final resort, fires the AppDomain.AssemblyResolve event. If none returns a match, the CLR throws an exception.


Loading Assemblies

To load an assembly from a filename, call LoadFrom or LoadFile.

To load an assembly from a URI, call LoadFrom.

To load an assembly from a byte array, call Load.


if an assembly with the same identity has already been loaded into memory from another location, LoadFrom gives you the previous copy, LoadFile gives you a fresh copy.

Load twice from an identical location, however, both methods give you the previously cached copy.


Loading an assembly twice from an identical byte array gives you two distinct Assembly objects.


LoadFrom hints the CLR as to the location of onward references, whereas LoadFile does not.


Statically referenced types – when one assembly reference a type (directly from source code) from another assembly.

Dynamic type reference – when one assembly loads dynamically another and create instance of type through Activator.CreateInstance (or in some other way).

It is called resolution context – in case this approaches are mixed – two different copies of assembly will be loaded.


Whether you use LoadFrom or LoadFile, the CLR always looks first for the requested assembly in the GAC. You can bypass the GAC with ReflectionOnlyLoadFrom (which loads the assembly into a reflection-only context). Even loading from a byte array doesn’t bypass the GAC, although it gets around the problem of locking assembly files:

byte[] image = File.ReadAllBytes (assemblyPath);

Assembly a = Assembly.Load (image);


If loaded from the Internet, where CodeBase is the Internet URI and Location is the temporary path to which it was downloaded. Another special case is with shadow copied assemblies, where Location is blank and CodeBase is its unshadowed location.


Packing a Single-File Executable – it is possible to pack all dependent assemblies as resources into main binary and loads them from there.


Reflection and Metadata


System.Type represents the metadata for a type

Type t1 = DateTime.Now.GetType(); // Type obtained at runtime

Type t2 = typeof (DateTime); // Type obtained at compile time


Nested types can be obtained also.

Dictionary’2 – generic type name with two parameters after apostrophe

Byte* – for pointer types

Boolean& – for ref and out types


It is possible get interface list of interfaces that are inherited by some type.


Instantiating Types – two ways to dynamically instantiate an object from its type:

– Call the static Activator.CreateInstance method

– Call Invoke on a ConstructorInfo object obtained from calling GetConstructor on a Type (advanced scenarios)


It is possible to call methods dynamically – to make it faster it is possible to create a delegate on dynamically got method and call it multiple times.


Non-public members can be reached as well.


Assemblies can be loaded for reflection only.



Three types:

– bit-mapped (public, abstract, sealed, keywords), compiled into some bits at metadata

– custom (are extensible, others are not), compiled into blob fields, inherited from System.Attribute. Can be user created/

-pseudocustom – it is custom attribute, but created by framework


Dynamic codegeneration – code emitting: classes, methods, local variables, branching, assemblies (can be saved to disk).


Circular dependencies are solved with custom provided TypeResolve event handler.


Dynamic programming


Dynamic Language Runtime (DLR) to perform dynamic binding.


Creating dynamic object:

– implementing IDynamicMetaObjectProvider

– subclassing DynamicObject (override bool TryGetMember),


Interoperability with dynamic languages




it is permissions and cryptography



Sandboxing – Limiting the kinds of operations that partially trusted .NET assemblies can perform

Authorization – Limiting who can do what


Sandboxing uses code access permissions; authorization uses identity and role permissions.


Both CodeAccessPermission and PrincipalPermission implement the IPermission interface.


A PermissionSet represents a collection of differently typed IPermission objects.


PermissionsSet can be applied while loading external assembly into separate domain to limit its possible actions.

Regular Expressions


Are located at System.Text.RegularExpressions


Regular expressions are used for tasks such as:

Validating text input such as passwords and phone numbers

Parsing textual data into more structured forms

Replacing patterns of text in a document (e.g., whole words only)



Match m = Regex.Match (“any colour you like”, @”colou?r”);

Console.WriteLine (m.Success); // True

Console.WriteLine (m.Index); // 4

Console.WriteLine (m.Length); // 6

Console.WriteLine (m.Value); // colour

Console.WriteLine (m.ToString()); // colour


IsMatch method is a shortcut for calling Match


Regular expression options

i Ignores case (by default, regular expressions are case-sensitive)

m Changes ^ and $ so that they match the start/end of a line instead of start/end of the string

n Captures only explicitly named or explicitly numbered groups

c Forces compilation of regular expression to IL

s Makes . match every character (instead of matching every character except \n)

x Eliminates unescaped whitespace from the pattern

r Searches from right to left; can’t be specified midstream


Expression     |     Meaning                     |    Inverse (“not”)

[abcdef]     |    Matches a single character in the list     |    [^abcdef]

[a-f]        |     Matches a single character in a range     |    [^a-f]

\d        |     Matches a decimal digit Same as [0-9]    |    \D

\w         |    Matches a word character (by default,

varies according to CultureInfo.

CurrentCulture; for example, in English,

same as [a-zA-Z_0-9])            |    \W

\s         |    Matches a whitespace character

Same as [\n\r\t\f]                |    \S

\p{category}     |    Matches a character in a specified category     |    \P

.    |     (Default mode) Matches any character except \n     |    \n

.    |     (SingleLine mode) Matches any character         |    \n


Quantifier – ‘?’ – 0 or 1 occurance

Alternator – ‘|’ – Console.WriteLine (Regex.IsMatch (“Jenny”, “Jen(ny|nifer)?”)); // True

* Zero or more matches

+ One or more matches

{n} Exactly n matches

{n,} At least n matches

{n,m} Between n and m matches


Greedy (.*) Versus Lazy (.*?) Quantifiers


Zero-Width Assertions

Lookahead (?=expr)

Negative lookahead construct  (?!expr).

Lookbehind (?<=expr)

Negative lookahead (?<!expr)



^ Matches the start of the string

$ Matches the end of the string



Named groups

To name a captured group: (?’group-name’group-expr) or (?<group-name>group-expr)

To refer to a group: \k’group-name’ or \k<group-name>


Replacing Text

Regexp is used to find a word and then this word is replaced by specified word.

MatchEvaluator Delegate – obtains the matched word and returns the other word that should be used as replacement.


Splitting Text

It splits by matched words, it is possible to use zero-width assertion for zero-length delimiter.




The synchronization categories:


Exclusive locking – just one thread to perform some activity or execute a section of code at a time. Constructs are lock, Mutex (and SpinLock).


Non-exclusive locking – lets you limit concurrency: Semaphore(Slim) and ReaderWriterLock(Slim).


Signaling – allow a thread to block until receiving one or more notifications from other thread(s): ManualResetEvent(Slim), AutoResetEvent, CountdownEvent and Barrier.


Nonblocking synchronization constructs – Thread.MemoryBarrier, Thread.VolatileRead, Thread.VolatileWrite, the volatile keyword, and the Interlocked class.


lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit. Monitor.Enter is overloaded with argument that specifies whether their locking was obtained at all. Monitor.TryEnter – allows specifying time span that allowed for getting into locked section, and returns true on success, otherwise – false. With zero timespan – it is possible to test whether at all the monitor can be locked.


Sync object – any referenced type, even local variables captured by lambda expressions or anonymous methods.


lock (typeof (Widget)) { … } – For protecting access to statics


When to lock – any writable shared field


Nested locking and deadlock.


Mutex – crossprocess lock (slower than locking in ~50 times).


WaitOne – to lock, ReleaseMutex – to unlock.


Common pattern throughout the .NET Framework: static members are thread-safe; instance members are not. But it should be code manually.


Immutable objects – with readonly fields.


Non-Exclusive Locking – Semaphore


SemaphoreSlim – for one process only.

Semaphore differs from lock and Mutex at fact that it can be locked and released by different threads.


ReaderWriterLockSlim – has different types of locking for reading and writing – simultaneous reading is allowed, writing is not (recursion supported).


Events – AutoResetEvent, ManualResetEvent(Slim), and CountdownEvent.


CountdownEvent lets you wait on more than one thread. Threads are stopped until event will not be signaled specified amount of times.


ThreadPool.RegisterWaitForSingleObject – it is possible to subscribe for event some delegate.


It is possible to convert event into task.


Wait functions – WaitAny, WaitAll, and SignalAndWait.


The Barrier class implements a thread execution barrier, allowing many threads to rendezvous at a point in time.


Lazy Initialization


Expensive _expensive;

readonly object _expenseLock = new object();

public Expensive Expensive




lock (_expenseLock)


if (_expensive == null) _expensive = new Expensive();

return _expensive;





two CLR solutions – Lazy<T> and LazyInitializer (through static member).




– [ThreadStatic] static int _x;

– ThreadLocal<T>

– GetData and SetData


Interrupt forcibly releases a blocked thread, throwing a ThreadInterruptedException on the thread.


Abort attempts to forcibly end another thread, throwing a ThreadAbortException on the thread right where it’s executing (unmanaged code excepted).


Suspend and Resume freeze and unfreeze another thread, to get a stack trace for example.



System.Threading.Timer and System.Timers.Timer – are general-purpose multithreaded timers.

System.Windows.Forms.Timer (Windows Forms timer) and System.Windows.Threading.DispatcherTimer (WPF timer) timers single threaded special.


Parallel programing


Structured data parallelism – PLINQ and Parallel class

PLINQ -like LINQ but paralleled via AsParallel method (can be inverted by AsSquential)

For local collections only.


PLINQ query can be canceled  via cancellation token.


PLINQ can be optimized by specifying a function that will be used instead of collating results.


It is possible to specify different partitioning strategies – for optimizing purposes.


The Parallel Class

PFX provides a basic form of structured parallelism via three static methods in the


Parallel.Invoke – Executes an array of delegates in parallel

Parallel.For – Performs the parallel equivalent of a C# for loop

Parallel.ForEach – Performs the parallel equivalent of a C# foreach loop



LongRunning – dedicated thread for such task

PreferFairness – tasks are started as they scheduled in same sequence

AttachedToParent – parent task waits for any child task for completion, exception of child’s task will be aggregated.


Task.WaitAll – if one or more of the tasks throw an unhandled exception, WaitAll still waits out every task—and then re-throws an AggregateException that accumulates the exceptions from each faulted task.


TaskContinuationOptions.OnlyOnFaulted, TaskContinuationOptions.NotOnFaulted – can adjust behaviour of continuations.


Conditional continuations – ContinueuWhenAll, ContinueuWhenAny, MultipleContinuations


Task scheduler allocates tasks to threads and is represented by the abstract TaskScheduler class.


It is possible to create own task factories with specified properties – like TaskCreationOptions.LongRunning, TaskCreationOptions.AttachedToParent, TaskContinuationOptions.None.


AggregateException contains actual InnerExceptions. There is several useful methods: Flatten (converts exception tree into sequence) of Handle (filters what types of exception should caught)


Concurrent Collections



ConcurrentBag<T> – stores an unordered collection of objects (with duplicates permitted), works faster in hard multi-threaded environment, each thread gets it own private linked list.



If you enumerate over a concurrent collection while another thread is modifying it, no exception is thrown—instead, you get a mixture of old and new content.


IProducerConsumerCollection<T> is implemented by concurrent collections, except ConcurrentDictionary.


BlockingCollection<T> – blocking collection wraps any collection that implements IProducerConsumerCollection<T> and lets you Take an element from the wrapped collection—blocking if no element is available.


Application Domains


AppDomain newDomain = AppDomain.CreateDomain (“New Domain”);

newDomain.ExecuteAssembly (“test.exe”);

AppDomain.Unload (newDomain);


DoCallBack – executes on another application domain, a method on a given type


Monitoring Application Domains





Sharing Data Between Domains – via Slots, Intra-Process Remoting,