Asychronous Programming Flashcards
What happens when you run long-processing routines in the main thread?
It hangs the application (app stopped working).
What is the difference between webclient and httpclient?
Webclient is legacy and HTTP client supports async methods.
How to use asynchronous code in a method?
The method needs to be declared as async and then within this method you can now call the await operator which will run the operations asynchronously.
What does the await operator do?
It runs the method after the keyword in an asynchronous method. It will wait (without blocking main thread) until the call returns before continuing to run the code.
What are the different types of asynchronous programming in C#?
The traditional which means manipulating threads and background workers (event-based asynch pattern). And the current way, which is via task parallel library via async away keywords.
Can we leverage the async await mechanism by simple adding an async operator in the slow method?
No… it’ll have no effect. Even the compiler will hint you to add at least one await within the method.
When are the common scenarios to use async await?
For I/O operations, such as Disk, Memory, Web/API and Databases.
What happens when you call the Result (or wait()) method of the returned task created by call of the async method? How to fix it?
It will execute synchronously and the UI will no longer respond until finished - sometimes causes DEADLOCK. Fixed by calling await instead.
Why some methods are called MethodX and some MethodXAsync?
In the past it was very common to both be used, but nowadays pretty much most of the heavy stuff be ran asynchronously.
What is the gain of using async await in a rest api? Aren’t all web api calls async from the caller perspective?
The gain is the the webserver will have a performance boost once the web server is freed to do something else.
What is the so called continuation?
Is the code that needs to be called after the await method finishes (has returned value).
Where the continuation is called? Will it restore the previous thread context?
The continuation is called in the original context (often UI thread). Yes, it restores the context before creating this artificial asynchronous operation (await)
Does the response of an await method allow for checking for success status codes?
Yes… just call EnsureSuccessStatusCode(); when the status code is not correct, it raises an exception. remember to handle it.
Should we use async VOID methods?
No. Avoid at any cost. Only allowed for event handlers and delegates (e.g, button click)!!!! Also, make sure all the exceptions are try catched inside this async method.
What is the proper way of declaring an async method?
public async Task myMethod(){}