C# Async Flashcards
1
Q
Asynchronous vs Parallel Programming
A
- these are not the same thing
- they can be used in conjunction
- you can fire off async job that runs pieces in parallel
- metaphor of async and parallel - boiling eggs
2
Q
What is AJAX?
A
- Asynchronous JavaScript and XML
3
Q
What is the TPL?
A
- Task Parallel Library
- introduced in .NET 4.0
- in System.Threading.Tasks
- introduced the Task.Run functionality
4
Q
What is Task.Run?
A
- takes an Action (no return) or a Func (return)
- always returns a Task so you can use Continuation
5
Q
What does an Anonymous Function look like?
A
() => { do stuff here }
6
Q
Task.Run and UI thread?
A
- Task.Run operates on a different thread so UI interactions must be properly handled
- depends on the platform
- ex. UWP uses Dispatcher.Invoke() which can interact with UI thread
7
Q
How about Task.Result?
A
- returns result of the Task
- this WILL block the UI thread until the Task completes
- this can be a cause of deadlocking if UI thread is locked but a Task tries to interact with UI thread
8
Q
What is Task.IsFaulted?
A
- this will tell you if a Task has completed due to unhandled exception
9
Q
What is Task.ConfigureAwait?
A
- ConfigureAwait(true) is the default and will attempt to marshal the thread back to the original calling context
- using ConfigureAwait(false) can save resources by staying on the current thread
10
Q
How about async/await?
A
- introduced in .NET 4.5
- add async keywork to methods
- marking method as async doesn’t mean everything runs async
- using await before a task is like scheduling Continuation
- using await the Continuation runs on calling context
- async operations fire up a state machine (expensive) to keep track of async ops
11
Q
What about async method returns?
A
- async methods should always return a Task or Task
- void is unacceptable except on event handlers
12
Q
How about Task.WhenAll()?
A
- use this to await more than 1 task completing
13
Q
What about the State Machine?
A
- every time you use async keyword a State Machine is created
- you can drill into this using something like .NET Reflector
- complex and expensive object
- using a lot of awaits introduces complexity into the state machine
14
Q
What is a deadlock example?
A
- use Task.Wait() which locks UI thread
- the Task fired is trying to access the UI thread, which is now locked
- this equates to a deadlock
- Task.Wait() and Task.Result() both will block UI thread
- if necessary some things must be wrapped in a new task