Understanding context in async and await.

Sumeet More
2 min readNov 17, 2019

--

While using await and async I always have that idea when I do await dosomework() it will be executed in background and my current thread will be signalled once work is done and current thread then will continue execution and this way we don’t block any thread.

But I always had that question how does current thread knows that work is completed in background. Answer is synchronizationcontext.

Let’s see an example.

what we are trying to do here is when button is clicked some work is done asynchronously and rest execution is continued on UI thread. In this case current thread is UI thread and our question is how this UI thread communicates with background work and coordinates.

Here is version without async and await doing same thing. Here what we did

  1. Capture current execution context(thread information and all).
  2. Submit work to threadpool
  3. Complete work.
  4. Use captured current context and tell work is done
  5. Continue rest execution on current thread(UI thread)(Post method of synchronizationcontext is used to make that transition)

Now you know when you write async and await you know how background work and main thread talk to each other and work is completed.

Happy Coding ☺

--

--

Sumeet More
Sumeet More

Written by Sumeet More

Software Engineer 2 at Microsoft | Backend Engineer and Architect| Blockchain & ML enthusiast | C#,.NET Core, Rust, Javascript and Go

No responses yet