Asynchronous Programming
Asynchronous Programming
The core of asynchronous programming is the Task and Task<T> objects which model
asynchronous operations.
Start a background thread using [Link] and await its result using await.
Start a background thread using [Link] and await its result using await.
Reference
Asynchronous programming - C# | Microsoft Docs
Overview
A program is a collection of statements and it is packaged in an EXE after it’s compiled. We take
a program like that, load it into memory and then we want to execute the statements in that
program.
Now, the thing that’s running that code, we usually can call it a thread now
So, Operating System runs on hardware. Within that Operating System, we have a process and
the process is launched. One of the threads in the process will start executing our statements.
Threads
Asynchronous implies multithreading programming. Multithreading means more than one part
of code is getting executed at a time.
Threads have stack (Thread Local). When you have multiple threads, then you have multiple
stacks. This is in contrast to heap, which is a shared memory where multiple threads can get to.
We are not in charge of when and in which order our threads will run.
Thread Safety
When two threads can run through a piece of code safely at the same time without interfering
with each other, then we would consider that method to be thread safe
Race condition
Asynchronous
Threads
using System;
using [Link];
namespace Threads
{
class Program
{
static void Main(string[] args)
{
[Link]("Starting in the Main method");
[Link]("Hello World!");
var t = new Thread(new ThreadStart(DoWork));
[Link]();
[Link]("Ending in the Main method");
}
}
}
}
What could go wrong?
1. Shared and/or mutable state – You end up in race condition
2. Locks and potential deadlocks
SHARED STATE
When a same variable is accessed by more than one threads, it may end up in race condition giving in
correct output
Race condition
Race condition occurs when two or more threads are able to access shared data and they try to change it
at the same time
To avoid this, we can have locks and there is a risk of having deadlocks.
Lock
It helps to wrap a piece of code and thereby keeps multiple threads accessing the piece of code at the
same time
using System;
using [Link];
using [Link];
namespace ConsoleApp1_Threads
{
class Program
{
static void Main(string[] args)
{
[Link]("Starting in the Main method");
[Link]("Hello World!");
var t = new Thread(new ThreadStart(AddList));
[Link]();
Thread Pool
Signaling
WAITHANDLE
MANUALRESETEVENT
Task
A promise of work happening asynchronously
Task Benefits
Auto-tuning the ThreadPool
More Control:
- Status, return values, cancellation, exception handling, custom scheduling and continuation
Semaphore
SemaphoreSlim
Reference
[Link]
Mutex