Thursday, October 03, 2019

Async and Await notes

- Await Keyword introduces continuation which is executed after the async operation 
- The coninuation is executed on the original context in this example that is the UI thread. 
- The await keyword introduces a coninuation allowing to get back to original context. 
- Marking a method as async introduces the capability of using the await keyword to leverage the asynchronous principles. 
- Avoid async void at all cost 
- Using Async void is allowed only for Event HAndlers 
- Methods marked as async taks will automatically have a Task returned without explicitly having to return anything,  then the caller can await the Task 
- If we do not use await keyword on async methods the inner exceptions will be swallowed. Always use the await keyword to validate your tasks. 
- Exceptions occuring in an async void cannot be caught 
- Do Not 
- No Async void 
- Avoid .Result or .Wait 

- Do 
- Async and Await together 
- Always return a Task from an Async method 
- Async and await all the way up. 

- Task Represents an asynchronous operation 
- Task.Run() queues the work passed as the action to run on a different thread by using the thread pool 
- Before Loading 
- Task.Run() queues the work which completes instantly 
- After Loaded --> Executes immediately after Task.Run()
- A task can easily for block the UI so be very careful when wrapping synchronos code and make sure it does not contain blocking code
- ContinueWith creates a continuation which runs asynchronously this means that it also returns a Task. 
- Calling the Result property on a task is not a problem as long as the task has finished its asynchronous operation. 
- A big difference between using await and ContinueWith is the fact that ContinueWith is not back on the original context.
- In case of ContinueWith if there's an error in the async operation then we need to define the TaskContinuationOptions to specify what needs to be done in case of exception. 
- Using await together with try and catch is recommended and does not wrap exception in an aggregate exception. 
- Whenever you use the ContinueWith make sure to validate tasks even when not using async and awat by chaining on a continuation, 
- CancellationTokenSource is used to signal that you want to cancel the operations that utilize the token.
- CancellationTokenSource is coupled with CancellationToken which is passed to async operations to indicate that operation is cancelled or not. 

No comments:

Post a Comment