- Published on
Async/Await in .NET - Things I learned #2
- Authors
- Name
- Tylah Kapa
- @jadekapa
Let's continue on from Part 1 of Async/Await in .NET.
5 more things that I learned while watching this video
ManualResetEventSlim
is a C# class that represents a "thread synchronization event".Using the
yield
keyword to return aMyTask.Delay()
can then be "awaited"MyTask
uses itself a remarkable amount in order to implement much of its functionsMyTask
implementsAwaiter: INotifyCompletion
which allows it to be awaited using the actualawait
keywordHow
Wait()
is implemented- Checks if
_completed
- Creates a
ManualResetEventSlim
if not_completed
. This can then be waited on - If exception is not null, will use
ExceptionDispatchInfo.Throw()
to append the error to the StackTrace
- Checks if
How
Run()
is implemented- Creates a new
MyTask
- Queues the action in
MyThreadPool
- Executes
action()
- Catches exceptions if needed
- Calls
SetResult()
- Creates a new
How
WhenAll()
is implemented- Takes a
List<MyTask> t
- Creates a new
MyTask
- Loops through the list of tasks and adds an
Action
continuation to each task - Decrements a counter when a task is completed using
Interlocked.Decrement(ref _count)
- Calls
t.SetResult()
when_count
is 0
- Takes a
How
Delay()
is implemented- Creates a new
MyTask
- Uses a
Timer
to callSetResult()
after a certain amount of time
- Creates a new
Conclusion
There's an exceptional amount of work that the Task
class does to be generic. But it remains relatively simple at its core.
The great takeaway from this video is to know that you don't need to deep-dive on everything. But it's always great to look one level under the hood and just take a look at how the tools you use every day work.