Monday, October 16, 2017

Async in C#

Tips

A thread is a relatively heavy weight structure. 1 thread takes 1M of Stack Space. A task is NOT a thread. You can have multiple tasks running on a single thread (such as UI thread).

Task.Delay() is like Thread.Sleep(), but it is a Task that won't complete for a specified amount of time.

The keyword async is not part of the method signature. For example, it doesn't show up in interfaces. It is convention to add Async to the end of a method name though. This tell the reader it is async.

Return Task, not void.

await

Frees thread to do other things such as update UI, etc. Before await is called the stack trace is in the method you called it from which makes sense. The potentially surprising thing is that the line after the await does NOT have the same stack trace. It is now in the same thread, but clearly not in the same calling method anymore. This is because the compiler creates a state machine when the code is complied. It's building what would have been done by hand before we had the keyword await in C#.
  • await frees a thread while we wait for an operation to complete. For example, handle another request in web scenario, update UI thread in desktop scenario. 
  • It does NOT block the thread, it actually frees the thread to do something else. 
  • The execution is stopped until the task is complete. 
  • When the task is complete the thread gets focus and execution continues. This is similar in concept to a callback after something is complete.

Exception Handling

If there is an exception in an async method it will be thrown and can be caught as if it was not an async method. For example, a simple try-catch.

1 comment:

vinothika0895@gamil.com said...

Its an awesome article. written in very creative way and it also conveys useful information.

Selenium Training in Chennai