Asynchronous Code Wrangling, Demo Code
While the talk was mostly live-coded, and will have some differences from what was presented, this repo covers those same asynchronous concepts.
- Locking up the UI thread with a long-running synchronous operation.
- [fail1] Wrapping with a
Task.Run
is good, but modifying the UI from outside the UI thread will blow up. - [fail2] Not waiting on the task result will produce inconsistencies.
- [fail3] Coming back to the UI thread too soon in a task will result still lock it up.
- [success1] Return to UI thread after long-running work will work out.
- [success2] Return to UI thread in task continuation will work out.
- [success3] Return to prior synchronization context (UI thread, in this case) will work out.
- Locking up the UI thread allows for traditional try/catch.
- Traditional try/catch will not catch errors inside your tasks. (As demoed, not in code.)
- Not handling errors properly
- [success1] Using
Task.IsFaulted
andTask.Exception
gets the tasksAggregateException
. - [success2] Adding a task continuation that only runs when the task fails.
- Clearing out the task overhead by switching to
async
/await
. - Using
try
/catch
withasync
/await
keeps things really clean.
This was a complex example of working with tasks and async
/await
together to make a fun keypad system. Entering the right combination will "unlock" the keypad.
- [Close] Creates a chain of
await
ed tasks based on the combination, but can be brute-forced because incorrect combination progression doesn't reset the chain. - [Better] Properly handles resetting for invalid combinations at the sake of a few more lines of event-handling code.
*[Note: the bug that was present in the live demo, where an incorrect last digit still unlocked the keypad, has been fixed.]
- Task helper method for legacy
Begin*
/End*
code. - Using
TaskCompletionSource
to work with old callback-based code.