Objective 1.1: Implement multithreading and asynchronous processing Flashcards

0
Q

What is the problem with single-threaded applications?

A

Long running operations and unrecoverable errors can freeze the rest of the machine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

What is parallelism?

A

The use of multiple threads in an application so as to take advantage of multi core systems and stay responsive.
Involves taking a certain task and splitting it into a set of related tasks that can be executed concurrently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a process?

A

Isolates an application from other applications by giving it its own virtual memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a thread?

A

Is like a virtualized CPU.

Each process run in its own thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is context switching?

A

Windows executes each thread for a certain period of time, after which the thread is paused and a new thread is switched in.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the disadvantage of context switching?

A

There is a performance overhead as each thread uses a certain area of memory, CPU registers and other state data, and Windows must ensure that the whole context is saved and restored on each switch.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Thread class?

A

Allows to create new threads, manage their priority, get their status and various other advanced options.
However it shouldn’t be used unless absolutely necessary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is synchronization?

A

Mechanism of ensuring that two threads don’t execute a specific portion of the program at the same time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Thread.Join used for?

A

It is invoked on a Thread instance and within another thread, e.g., the main thread. This will force the main thread to wait for the other thread to finish.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the default priority of a new thread?

A

Normal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the use of Thread.Sleep(0)?

A

Signals Windows that the thread is finished, so that it can immediately switch to another thread, instead of waiting for the whole time slice of the thread to finish.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between foreground and background threads?

A

Foreground threads can be used to keep an application alive.
Only when all foreground threads end will the CLR shut down your application.
Background threads are then terminated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the ParameterizedThreadStart class used for?

A

An instance of this, when passed into the Thread constructor, is used when you want to pass some data through the start method of your thread to your worker method.
Data is passed as an object and will need to be parsed to be usable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the Thread.Abort method used for?

A

Used to stop a thread, at which time a ThreadAbortException is thrown on the target thread.
It is recommended to avoid this and use a shared variable instead for stopping a thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a lambda expression?

A

Short hand version of a delegate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of the ThreadStatic attribute?

A

When a field is marked with this, it allows each thread to get its own copy of it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the purpose of the ThreadLocal class?

A

Class that takes a delegate to a method that initializes a value, in the event that you want to use local data in a thread and initialize it for each thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the purpose of the Thread.CurrentThread class?

A

Gives execution context of the thread that is currently executing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What information exists in the execution context?

A

Current culture is a CultureInfo instance associated with the current thread that is used to format dates, times, numbers, currency values, the sorting order of text, casing conventions, and string comparisons.
Principal represents the current security context.
Priority indicates how the thread should be scheduled with the OS.
Etc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the purpose of the ExecutionContext.SuppressFlow method?

A

Prevents the initiating threads execution context to be flowed to the new thread, as the copying of data could cost some resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is a thread pool?

A

Created to reuse threads as the creation and cleanup of new threads costs time and resources.
In .NET you queue a work item which is then picked up by an available thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are the pros and cons of thread pools?

A

Manages the creation and disposal of threads as needed, i.e., starts out empty and can be empty after a long time.
Local state is reused since threads are reused.
Lesser degree of parallelism so server can become unresponsive, but helps prevent server crash.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a Task?

A

Object that represents some work that should be done. Unlike Threads, it can tell you if the work is completed, and it’s return result (if any).
Recommended way to create multithreaded applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is a Task Scheduler?

A

Responsible for starting a task and managing it, and by default does so by using threads from the thread pool.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the purpose of Task.Wait?

A

Waits for the task to complete before exiting the application, much like Thread.Join.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the Task class used for?

A

Used instead of the Task class to return a value.

26
Q

What happens when calling Task.Result?

A

It will force the thread trying to read the result to wait until the Task is finished before continuing, and if the Task is not yet finished, this call will block the current thread.

27
Q

What is a continuation task?

A

Task that is set to execute as soon as another task is complete.

28
Q

What are the overloads for the Task.ContinueWith method?

A

TaskContinuationOptions.OnlyOnCanceled
TaskContinuationOptions.OnlyOnFaulted
TaskContinuationOptions.OnlyOnRanToCompletion

29
Q

How do parent tasks work?

A

It finishes when all child tasks are ready.

30
Q

What is a TaskFactory?

A

Created with a certain configuration and can then be used to create Tasks with that configuration.

31
Q

What is the purpose of Task.WaitAll?

A

Static method that is used to wait for multiple tasks to complete before continuing execution.

32
Q

What is the purpose of Task.WhenAll?

A

Used to schedule a continuation method after all tasks have finished.

33
Q

What is the purpose of Task.WaitAny?

A

Continues when any task is completed, returning the index of the task when referenced from an array.

34
Q

What is the purpose of the Parallel class?

A

It has static methods that can be used to parallelism work.
For, ForEach, Invoke
Only beneficial if there is a lot of work that can be executed in parallel; using it on smaller work sets will hinder performance.

35
Q

What are the uses of the ParallelLoopState object?

A

Used to cancel the parallel loop either by a Break, which ensures that all iterations that are currently running will be finished, or by a Stop, which just terminates everything.

36
Q

What is the state of IsCompleted and LowestBreakIteration when using Break and Stop?

A

Using Break, IsCompleted=false and LowestBreakIteration=500.

Using Stop, LowestBreakIteration=null.

37
Q

What happens when your application is executing an I/O operation on the primary thread?

A

Windows pauses the thread so that it doesn’t use any CPU resources, but the thread is still using memory so new threads can still be spawned for new requests.

38
Q

What is the purpose of the async keyword?

A

Used to mark a method for asynchronous operations, signaling the compiler of this, who then responds by transforming the code into a state machine.
Method will still run synchronously.

39
Q

What is the purpose of the await keyword?

A

Marks an operation to be run asynchronously within the method marked with the async keyword.
Operation will run as a Task, and as such the async method should return a Task or Task, instead of void, which should only be used for async event handlers.

40
Q

What is the difference between a CPU-bound task and an I/O-bound task?

A

CPU-bound tasks always use some thread to execute their work, whereas an I/O-bound asynchronous task doesn’t use a thread until the I/O is finished.

41
Q

What happens when an exception is thrown in an asynchronous method?

A

An AggregateException is thrown.

42
Q

What is the SynchronizarionContext?

A

Connects an application model to its threading model.
Using the await keyword ensures that the current SynchronizationContext is saved and restored when the task finishes.
Can be disabled by using ConfigureAwait(false).

43
Q

What is LINQ and PLINQ?

A

Parallel language integrated query.
LINQ is used to perform queries over all kinds of data.
PLINQ can be used on objects to potentially turn a sequential query into a parallel one.

44
Q

Where are the extension methods for using PLINQ defined?

A

System.Linq.ParallelEnumerable.

45
Q

What is the purpose of the WithExecutionMode method?

A

Forces a PLINQ query to run in parallel mode, otherwise the runtime determines whether it needs to.
If it does, it generates Task objects and starts executing them.

46
Q

What is the purpose of the WithDegreeOfParallelism method?

A

Limits the amount of parallelism that is used, by specifying the number of processors to use, otherwise it will use all (up to 64).

47
Q

What is the disadvantage of parallel processing?

A

It does not guarantee any particular order.

48
Q

What is the purpose of the AsOrdered method?

A

To ensure that the results from parallel processing are ordered, which is done by buffering and sorting the results.

49
Q

What is the purpose of the AsSequential method?

A

Allows you to ensure some parts are to be processed sequentially.

50
Q

How does the ForAll operator work?

A

Iterates over a collection when it can be done in a parallel way.
Doesn’t need all results before it starts executing.
Removes any sort order that is specified.

51
Q

How does one handle exceptions from parallel processing?

A

All exceptions are aggregated into a single AggregateException.
The InnerExceptions property will list all specific exceptions.

52
Q

What are thread-safe collections?

A

They internally use synchronization to make sure they can be accessed by multiple threads at the same time.

53
Q

List the thread-safe collections?

A
BlockingCollection
ConcurrentBag
ConcurrentDictionary
ConcurrentQueue
ConcurrentStack
54
Q

Describe BlockingCollection?

A

Removing items can be blocked until data is available.
Adding data is fast, unless am upper limit is specified and reached, after which there is blocking until there is room to add.
Unless otherwise specified, it uses ConcurrentQueue by default.

55
Q

What is the purpose of the BlockingCollection.CompleteAdding method?

A

Signals the BlockingCollection that no more items will be added, so if other threads are waiting for new items, they won’t be blocked anymore.

56
Q

What does GetConsumingEnumerable do?

A

Returns an IEnumerable that blocks until it finds a new item.

57
Q

Describe ConcurrentBag?

A

Bag of items, that enables duplicates and has no particular order.
It’s TryPeek is not useful in a multithreaded environment since another thread could remove the item before you access it.
Implements IEnumerable so it can be iterated, at which point a snapshot is taken of the collection.

58
Q

What is the difference between Stack and Queue?

A

Stack is LIFO and Queue is FIFO.

59
Q

List the useful methods of ConcurrentStack?

A

Push, TryPop, PushRange, TryPopRange.

60
Q

List the useful methods of ConcurrentQueue?

A

Enqueue, TryDequeue, TryPeek.

61
Q

How does ConcurrentStack and ConcurrentQueue implement IEnumerable?

A

Takes a snapshot of the collection.

62
Q

Describe the ConcurrentDictionary?

A

Stores key-value pairs in a thread-safe manner.
Has methods to atomically add, get and update items.
TryUpdate checks the value before updating it.
AddOrUpdate, GetOrAdd also exist.