What is a thread?
Each application in Windows runs its own process. Each process runs its own thread. A thread is something like a virtualized CPU.
What is parallelism?
Execute multiple threads on different CPUs in parallel
What is context switching?
As a thread expires it switches to another thread. This is called context switching
Why should you be careful using multithreads?
Because of the risk of overhead.
Thread Class namespace:
System.Threading
What is the ThreadStatic attribute?
With the ThreadStatic attribute you can mark a field and then each thread gets its own copy of a field.
What can you do with a ParameterizedThreadStart delegate?
Pass data to the start method.
Why shouldn't you use Thread.Abort to stop a thread?
A ThreadAbortExeption is thrown on the target thread. This can potentially leave a corrupt state and make your application unusable.
What does t.Join do?
Wait for a thread to finish execution.
What's the difference between ThreadStatic and ThreadLocal<T>?
ThreadStatic doesn't automatically initialize things for every thread
What is execution context?
Information about the thread that's executing.
Has a new thread the same privileges as the parent thread?
Yes
Can you disable the behavior to copy privileges to a new thread?
Yes, by using the ExecutionContext.SuppressFlow
What is the purpose of a thread pool?
To reuse threads: Send a thread back to the threadpool where it can be reused whenever a request come in.
What is the advantage of the Thread Class in relation to a Thread Pool?
You get a better degree of parallelism because the thread pool limits the available number of threads.
What is the advantage of the Thread pool for web servers?
The Thread Pool ensures that each incoming request gets added to the queue and that when a thread becomes available, it is processed. If you do this manually you could easily bring down your server if you got a lot of requests. But if your ran out of thre
What happens with threads in the Thread Pool from beginning to the end?
First a Thread Pool is empty. As a requests come in it creates additional threads to handle those requests. If the threads are no longer in use for a time it can kill those threads for more recourses.
What is the danger of reusing threads?
If a thread is being reused then its also reuses its local state. You can not rely on state that can potentially be shared between multiple operations.
What is responsible for starting the Task and managing it?
A Task Scheduler. Default: The Task Scheduler uses threads from the thread pool to execute the task.
What is the purpose of a task?
To make your application more responsive.
What does t.Wait do?
The same as t.Join, it waits till the Task is finished before exiting.
What should you use if a Task has to return a value?
Task<T>
What is a continuation task?
A way to indicate that another operation must execute as soon as a Task finishes.
Task<int> t = Task.Run(() =>
{
return 42;
});
t.ContinueWith((i) =>
{
Console.WriteLine("Canceled");
}, TaskContinuationOptions.OnlyOnCanceled);
t.ContinueWith((i) =>
{
Console.WriteLine("Faulted");
}, TaskContinuationOptions.OnlyOnFaulted);
var completed
Configure when the continuation will run. You can add different continuation methods that will run when an exception happens.
What is a TaskFactory?
A TaskFactory is created with a certain configuration and can then be used to create tasks with that configuration.
TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinutionOptions, ExecuteSynchonously)
tf.Startnew (() => resu
What does WaitAll?
Wait for multiple tasks to execute before continuing execution.
Task.WaitAll(tasks)
What is the difference between WaitAll, WhenAll, and WaitAny?
WaitAll: wait for multiple tasks to execute before continuing execution.
WhenAll: schedule a continuation method after all Tasks have finished.
WaitAny: Wait for one task to finish.
Parallelism
Taking a certain task and splitting it into a set of related tasks that can execute concurrently.
Methods Parallelism:
For, Foreach & Invoke
When do you use Parallelism?
If you have a lot of work to be done that can be executed in parallel.
It can hurt performance. Measure results to know if parallelism is the best way.
How do you cancel Parallelism?
Break or Stop
Async method
An asynchronousmethod is a method that does not block the current thread of execution
With 'async' you can mark a method for asynchronous operations > Compiler responds by transforming your code into a state machine
Why is work that's input/output (I/O)-bound different then long running CPU bound tasks?
When your application is executing an I/O operation Windows notice that your thread is waiting for the I/O operation to be complete. Because of this, windows pauses your thread so that it doesn't use any CPU resources. But it still uses memory and the thr
What can you best use if you have an application that executing an I/O operation?
Asynchronous code.
It doesn't block your thread, you get back a Task object that represents the result of the async operation. Your thread stays available for other work.
How does async work?
Starts running synchronously on the current thread. Enable the method to be split into multiple pieces.
Await
You can use this operator only inside a method marked as async. Its purpose is to release the current thread and wait for a task to complete in the background. When that task finishes, control returns to the method, which continues with the next statement
Yield
Yield helps to do custom stateful iteration over a collection. It allows each iteration in a foreach-loop be generated only when needed. In this way it can improve performance.
GetStringAsync
Returns a Task<string> to the caller
What is the difference between a CPU Bound task and an asynchronous I/O bound task?
CPU Bound tasks always use some thread to execute their work. An asynchronous I/O bound task doesn't use a thread until the I/O is finished.
Async & Await
This are markers which mark code positions from where control should resume after a task or thread completes.
Can the FileStream Class be asynchronous?
Yes, it has async methods as WriteAsync and ReadAsync that don't use a thread.
AggregateException
Exception in asynchronous method.
SynchronizationContext
Connect application model to its threading model.
For Example: A WPF app uses single user interface thread and potentially multiple background threads. But an ASP.NET uses threads from the threadpool.
ConfigureAwait(false)
Disable the flow of the synchronizationContext
Can you use async/await on a void return type?
You can better avoid this and choose a return type of Task or Task<T>. You can use async void only when dealing with asynchronous events.
Important rule for async and await.
You should never have a method marked async without await statements. You should also avoid returning void from an async method except when it's an event handler.
PLINQ
Turn a sequential query in a parallel one.PLINQ is an extension to LINQ to run queries in parallel.
WithExecutionMode
PLINQ: Query should always be parallel
WithDegreeOfParallelism
PLINQ: Limit parallelism
AsOrdered
PLINQ: Ensure that results are ordered
AsSequential
PLINQ: Stop parallelism query
ForAll
PLINQ: Iterate over collection parallel
TPL
Task Parallel Library
BlockingCollection<T>
Collection that is thread safe for adding and removing data..
- Adding data is fast.
- Removing data can be blocked.
- default: ConcurrentQueue
ConcurrentBag<T>
Threadsafe: A bag of items.
- enables duplicates
- No particular order.
- Methods: Add, TryTake & TryPeek (TryPeek :not very usefull in multithreaded environment)
ConcurrentDictonary<TKey,T>
Stores key value pairs in thread safe manner. Add, remove & update items.
Methods: TryUpdate, AddOrUpdate, GetOrAdd
ConcurrentQueue
First in, First Out collection
2 methods: Enqueue (add) & TryDequeue (remove)
ConcurrentStack
Last in, First Out collection.
2 methods: Push (add) and TryPop (remove) (PushRange, TryPopRange)
IEnumerator GetEnumerator();
The GetEnumeratormethod should return an enumerator object that implements the System.Collections.IEnumeratorinterface. The enumerator object is used for stepping through (enumerating) the elements of the collection.
The IEnumeratorinterface specifies the
Enumerator
Think of an enumerator as a pointer pointing to elements in a list. Initially, the pointer points
beforethe first element. You call the MoveNextmethod to move the pointer down to the next (first)
item in the list; the MoveNextmethod should return trueif t
Enumerator: Current & Reset
You use the Current property to access the item currently pointed to, and you use the Reset method to return the pointer back to before the first item in the list.
Atomic operation
An operation that will be started and finished as a single step without other threads interfering.
What's the benefit of multithreading if you use a webserver?
This can improve responsiveness in a client application
Does using multithreading with the TPL offer the same advantages for your server application?
Using multithreading in a server environment can help you distribute operations over multiple CPUs. This way, you can improve performance. Using the TPL to create another thread to execute a CPU-bound operation while the originating thread has to wait for
Multiple Threads
Using multiple threads can improve responsiveness and enables you to make use of multiple processors.
Threadclass
The Threadclass can be used if you want to create your own threads explicitly. Otherwise, you can use the ThreadPool to queue work and let the runtime handle things.
Taskobject
A Taskobject encapsulates a job that needs to be executed. Tasks are the recommended way to create multithreaded code
ParallelClass
The Parallelclass can be used to run code in parallel.
new async and await operators
The new async and await operators can be used to write asynchronous code more
easily.
Concurrent collections
Concurrent collections can be used to safely work with data in a multithreaded (concurrent access) environment.
lock operator
block threads while they are waiting for each other
- Use the lockstatement on a private object to synchronize access to a piece of code.
Deadlock
Threads wait on each other but never complete
Use 'lock' on value or reference?
Reference. Value type gets boxed > generates completely new lock each time.
Volatile
Force correct order in code.
Only use this when needed because it hurts performance and is not support by all .NET languages.
Interlocked class
Making operations atomic.
Interlocked.Increment.
Interlocked.Decrement.
You can use the Interlockedclass to execute simple atomic operations.
Interlocked.Exchange
Switching values: Retrieves current value and replaces it
Interlocked.CompareExchange
Check first if expected value is there and then replace it.
CancellatationToken > Task
Periodically monitors the token to see where cancellation is requested
You can cancel tasks by using the CancellationTokenSourceclass with a CancellationToken
OperationCanceldExeption
Signal to users that a task is been cancelled.
CancellationToken: Continuation Task
Executes when Task is cancelled.
How can you orchestrate your locking code to avoid deadlocks?
It's important to make sure that all locking follows the same order when locking multiple objects. As soon as you start locking dependent objects in different orders, you start getting deadlocks.
How can the Interlockedclass help you?
The Interlockedclass can help you to execute small, atomic operations without the need for locking. When you use locking a lot for these kind of operations, you can replace them with the Interlockedstatement.
synchronize access
When accessing shared data in a multithreaded environment, you need to synchronize access to avoid errors or corrupted data
Exclusive OR (XOR)
Returns true only if exactly one of the operands is true.
?? operator / null coalescing operator
Called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
conditional operator: ?:
Returns one of two values depending on a Boolean expression. If the expression is true it returns the first value otherwise the second.
return p ? 1 : 0
Jump statement: goto, break, continue
- You cannot make a jump to a label that's not in scope.
- If possible avoid jump statements (refactoring: you can remove them)
- Goto >> bad practice >> avoid
Iterating across collections
Int[] values = { 1,2,3};
For (int index = 0; index < values.length; index++)
{console.Write(values[index]);}
For(initial; condition; loop)
Short-circuiting:
If left side of an OR operation is true it doesn't have to evaluate the right part of the expression.
What's not allowed when using a foreach statement?
It is not allowed to change the value of the iteration variable in a foreach statement.
What is the disadvantage of using goto? How can you avoid using the goto statement?
Using the goto statement makes your code much harder to read because the application flow jumps around. goto is mostly used in looping statements. You can then
replace goto with while or do-while.
Which statement can you use to improve the long if statements?
The switch statement can be used to improve long if statements.
What are the differences between the for and foreach statement? When should you use which?
The for statement can be used to iterate over a collection by using an index. You can
modify the collection while iterating. You need to use the index to retrieve each item. foreach is syntactic sugar over the iterator pattern. You don't use an index; ins
Boolean expressions
Boolean expressions can use several operators: ==, !=, <, >, <=, >=, !. Those operators can be combined together by using AND (&&), OR (||) and XOR (^).
if-else
You can use the if-else statement to execute code depending on a specific condition.
switch
The switch statement can be used when matching a value against a couple of options
for loop
The for loop can be used when iterating over a collection where you know the number
of iterations in advance
while
A while loop can be used to execute some code while a condition is true; do-while
should be used when the code should be executed at least once
foreach
foreach can be used to iterate over collections.
Jump statements
Jump statements such as break, goto, and continue can be used to transfer control to
another line of the program.
Delegate
Type that defines a method signature. In c# you can instantiate a delegate and let it point to another method.
Instantiated delegate
Object that you can pass around and give it as an argument to other methods.
Multicasting
Combine delegates together
Add another method to the invocation list of an existing delegate instance.
Use + or +=
How many methods is a multicast delegate going to call?
int invocationCount = del.GetInvocationList().GetLength();
Delegate: Covariance
permits a method to have a return type that is more derived than that defined in a delegate.
Delegate: Contra variance
permits a method that has parameter types that are less derived that those in the delegate type.
lambda syntax
You can say go or goes to for the special lambda syntax.
Calculate calc = (x, y) => x + y;
Lambda expression
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
Benefits Lambda expressions
a.Reduced typing. No need to specify the name of the function, its return type, and its access modifier.
b.When reading the code you don't need to look elsewhere for the method's definition.
How do we define a lambda expression?
Lambda basic definition: Parameters => Executed code.
n => n % 2 == 1
FE:
List<int> numbers = new List<int>{11,37,52};
List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();
//Now oddNumbers is equal to 11 and 37
Built in delegate that does return a value
Func<int,int,int>
Delegate that doesn't return a value
Action
Closure
Life of captured variable is as long as the longest living delegate
Publish-subscribe
Design Pattern: Subscribe to an event and get notification
Properties of an 'event'
- It's public
- An event cannot be directly assigned to (with the = intead of +=) operator.
- No outside users can raise your event.
- Instead of using Action you should use the EventHandler or EventHandler<T>:
- The event is never null
public delegate vo
Custom event accessor
Customize addition and removal of subscribers.
You are working on a desktop application that consists of multiple forms. Those forms show different views of the same data and they should update in real time. Your application is extensible, and third parties can add plug-ins that contain their own view
Events are a nice layer on top of delegates that make them easier and safer to use. In this case, you should use events to make sure that other users won't be able to clear all
subscriptions. It also makes sure that they can't raise the event on their own
What kind of type is a delegate?
Delegates are a type that defines a method signature and can contain a reference to a method.
What can you do with delegates?
Delegates can be instantiated, passed around, and invoked
How do lambda expressions function?
Lambda expressions, also known as anonymous methods, use the =>operator and form a compact way of creating inline methods
What are events in relation to delegates?
Events are a layer of syntactic sugar on top of delegates to easily implement the publish-subscribe pattern
How do events raise?
Events can be raised only from the declaring class. Users of events can only remove and add methods the invocation list.
How do you customize events?
You can customize events by adding a custom event accessor and by directly using the underlying delegate type
Advantages Exceptions in relation to error codes:
#NAME?
Environment.FailFast(".....")
Preventing Finally block from running.
StackTrace
Describes methods that are currently in execution.
InnerExeption
Linking two exceptions.
Message
Message to describe exception.
HelpLink
URN or URL that point to a help file.
HResult
Describing severity error
Source
Name of app that caused the error.
TargetSite
Name of the method that caused the exception.
Data
Store extra data for your exception.
Throw new ArgumentNullException("FileName", "Filename is required")
Throw new exception
Three ways to rethrow an exception
1. Use the throw keyword without an identifier
2. Use the throw keyword with the original exception
3. Use the throw keyword with a new exception
Use the throw keyword without an identifier
Rethrow exception: No modifications to the exception
Use the throw keyword with the original exception
Rethrow exception: Reset call stack so you don't see where it came from. (Harder to debug)
Use the throw keyword with a new exception
Rethrow exception: raise another exception
Where should you be careful for when you are rethrowing an exception?
Make sure you don't swallow any exception details when rethrowing an exception. Throw a new exception that points to the original one when you want to add extra information; otherwise, use the throw keyword without an identifier to preserve the original e
Catch (FormatException ex)
{
possibleException = ExceptionDispatchInfo.Capture(ex)
}
ExceptionDispatchInfo: Throw an exception and preserve the original stack trace.
When should you create a custom exception?
You should create a custom exception only if you expect developers to handle it or perform custom logging. If a developer won't be able to fix the specific error, it won't make any sense to create a more specific exception. Custom logging can happen when
Explain to your colleague the advantages of Exceptions compared to error codes.
Exceptions are objects, so they can store extra information that can't be done with only an error code. The .NET Framework also offers special support for dealing with exceptions. For example, you can use catch blocks to handle certain types of exceptions
When to create a custom exception?
You can define your own custom exceptions when you are sure that users of your code will handle it in a different way. Otherwise, you should use the standard .NET Framework exceptions.
Custom Exceptions Inherits From:
System Exception
Criteria's custom exceptions:
public OrderProcessingException (int orderId, string message, Exception innerException)
- a parameter less constructor
- add a few constructors (string, string & exception, serialization)
System.ApplicationException
Never inherit from this namespace
multithreading: responsive and scalable.
Multithreading can help you create programs that are responsive and scalable. You can use the TPL, the Parallel class, and PLINQ for this. The new async/awaitkeywords help you write asynchronous code.
manage synchronization
In a multithreaded environment, it's important to manage synchronization of shared data. You can do this by using the lockstatement.
making decisions
C# offers statements for making decisions�if, switch, conditional operator (?) and nullcoalescing operator (??)�iterating (for, foreach, while, do-while), and jumpstatements (break, continue, goto, return and throw)
delegates-lambda expressions
Delegates are objects that point to a method and can be used to invoke the method. Lambda expressions are a shorthand syntax for creating anonymous methods inline
events-delegates
Events are a layer on top of delegates that help you with creating a publish-subscribe architecture
exeptions-errors
Exceptions are the preferred way to work with errors in the .NET Framework. You can throw exceptions, catch them, and run code in a finally block
Type
Blueprint for construction an object
3 Types in C#
Value types
Reference types
Pointer tyes
enum
public enum Gender { Malem, Female}
Create a list of possible options
Advantages enum
Readable and maintainability of your code.
enum Days : byte { Sat = 1, Sun, Mon, Tue}
Change the starting index of the enum
[Flags]
enum Days
{
Non = 0x0,
Sunday = 0x1,
Monday = 0x2
}
The [Flags] attribute on an enum allows you to assign multiple values to your enum at once. You can do this with bitwise manipulations, meaning you can store an enum with A and C set, not just A and not just C.
Value type
The value directly
Reference type
Reference to real value
Value of reference type is stored on the
Heap
A value type is stored on the
Stack
Except: class with value as one of it fields, a lambda expression or a value type that is boxed.
is operator
You can use the is operator to verify that the type of an object is what you expect it to be
as operator
Like the is operator, the as operator takes an object and a type as its operands. The runtime
attempts to cast the object to the specified type. If the cast is successful, the result is returned and, in
this example, it is assigned to the WrappedInt varia
Benefit of storing data in stack
Faster, smaller and doesn't need attention of garbage collector.
Three criteria to determine if you want to create a value type
The object is small.
The object is logically immutable,
There are a lot of objects.
Struct
Create a new value type with the 'struct' keyword. Other examples of struct(ures) are bool, int, char etc.
Differences between a class and a struct
- You can't declare a default constructor (a constructor with no parameters) for a structure
-In a class, you can initialize instance fields at their point of declaration. In a structure, you cannot.
struct Time
{
private int hours = 0; // compile-time er
When to use a value or reference type.
It's important to know the different types that are available in C#. A value type should be used for small, immutable objects that are used a lot. In other types use a reference type.
Function VS Method
Function: returns a value and doesn't modify (Read)
Method: Enable dat amodification and doesn't return data (Write)
In comparing:
Func<T> always returns
Action: returns nothing
Important steps when adding a method to your own type:
1. Choose a name for your method.
2. Decide which data should be passed to your method.
3. Decide which data you want to return to the caller.
4. Decide on the visibility of your method.
Named arguments
Specify which arguments you want to pass a value.
Optional arguments
public void DoWorkWithData(int intData, float floatData, int moreIntData)
{
...
}
public void DoWorkWithData(int intData, float floatData)
{
...
}
Enable you to omit arguments for some parameters. This can be useful when you want to specify default values for certain parameters.
Optional parameters are also useful in other situations. They provide a compact and simple solution when it is not possibl
overloading
Create methods with the same name that differ in arguments they take. (F.E. Console.WriteLine)
No access modifier
Default : private
Field
Variable of any type that is declared directly in a class or struct.
const
constant value
Indexer
For Example
List<int> mylist = new List<int>(){1,2,3};
myList[0] = 1;
enables instances of your class or struct to be used as arrays
Static
Not specific for an instance
Create methods and data that can be shared by all instances of the same class by using the
static keyword.
Why should you define your own constructors?
#NAME?
Good practices when designing your own constructors:
- Explicitly declare the public default construct in classes if such a constructor is required.
- Ensure that your constructor takes a few parameters as possible,
- Map constructor parameters to properties in your class.
- Throw exceptions from instance c
Design principles class:
#NAME?
SOLID
Single responsibility principle
Open/closed principle
Liskov substitution principle
Interface segregation principle
Dependency Inversion principle
Generics
Generic types use a type parameter to make the code more flexible.
where T: struct
The type argument must be a value type (only Nullable is not allowed).
where T : class
The type argument must be a reference type: for example, a class, interface, delegate, or array
where T : new()
The type must have a public default constructor.
where T : <base class name>
The type argument must be or derive from the specified base class.
where T : <interface name>
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic
where T : U
The type argument supplied for T must be or derive from the argument supplied for U.
default(T)
Gives you the default value for T
extension
enable new capabilities to an existing type.
Extensions are declared in:
public class Product
{
public decimal Price { get; set; }
}
public static class MyExtensions
{
public static decimal Discount(this Product product)
{
return product.Price * .9M;
}
}
public class Calculator
{
public decimal Calc
a nongeneric, non-nested, static class
Difference between static and extension
use of this in the first argument
Override method
class Base
{
public virtual int MyMethod()
{
return 42
}
}
class Derived : Base
{
public override int MyMethod()
{
return base.MyMethod() * 2;
}
}
Replace existing functionality or add behavior to base class
sealed
disable inheritance
virtual
A method that is intended to be overridden is called a virtual method.
What's the correct naming for types that you can use building a webshop?
Some of the types that you can use in building your web shop are: Order, OrderLine, Product, Customer, Review, SearchCriteria, BusinessRule
How can you make sure that your types contain both behavior and data?
When designing the system, you should focus on the behavior and then make sure that you have the data to support it. For example, instead of publicly exposing the OrderLines that an order contains, you should expose a method AddProduct(product, amount) th
How can you improve the usability of your types?
By making sure that you have the correct constructors, users of your types can easily see which data is required. By using enums (for example for the Orderstatus and Customerstatus), you can improve readability of your code. By using a base class for your
type
Constructors, methods, properties, fields, and indexer properties can be used to create a type.
Optional and named parameters
Optional and named parameters can be used when creating and calling methods
Overloading methods
Overloading methods enable a method to accept different parameters
Extension methods
Extension methods can be used to add new functionality to an existing type
Overriding
Overriding enables you to redefine functionality from a base class in a derived class
dynamic
enables weakly typed
string.Concat
adds arguments together and return them as a string
boxing
Taking a value type putting it inside a new object on the heap and storing a reference to it on the stack
unboxing
Taking the item from the heap and return a value type that contains the value from the heap
Implicit conversion
Conversion is allowed and safe to convert.
int I = 42
double d = I;
Explicit conversion
casting
double x = 1234.7;
int a;
// Cast double to int
a = (int)x; // a = 1234
casting
Explicit conversion and needs special syntax