Task/Async Flashcards

1
Q

Drawbacks of Threading

A

Complexity

Threading can be significantly more complex to manage than tasks. You have to deal with low-level thread creation, synchronization primitives (e.g., locks, mutexes) which can lead to more error-prone code.

Scalability

Threads are heavyweight resources, and creating too many of them can lead to excessive memory usage and decreased performance.

Cancellation

Implementation of cancellation that allows you to gracefully terminate ongoing operations is possible in threads; but it is too complex and inefficient.

Asynchronous Programming

Threads don’t support asynchronous programming out-of-box.

When you try to implement asynchronous I/O operations using threads, they tend to block the thread until the I/O operation completes. So it leads to overload on system resources.

Parallel Programming

Parallel programming allows you to execute the code parallelly on multiple CPU-cores, which is not supported by the threads.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Introduction to Tasks & TPL

A

The Task Parallel Library (TPL) is a set of APIs and runtime features, which provides a higher-level abstraction to implement concurrency, parallelism and asynchronous programming, which works based on threading.

TPL internally works based on “Thread Pool”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Tasks

A

The fundamental building block of TPL is the “Task”.

A Task represents an operation (method) that can be executed concurrently & parallelly with other tasks.

Tasks can represent both CPU-bound and I/O-bound operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How TPL Works Internally?

A

Task Creation

When you create a task, it gets scheduled by the Task Scheduler.

Task Scheduler

The ‘Task Scheduler’ is responsible for managing the execution of tasks. It determines how tasks are executed and which threads they run on.

Thread Pool

The Task Scheduler utilizes the Thread Pool to allocate and manage threads. It avoids the overhead of creating new threads for each task by reusing existing Thread Pool threads.

Concurrency Control

The Task Scheduler ensures proper coordination and scheduling of tasks to maximize CPU utilization and minimize contention for resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Features and Advantages of TPL

A

Abstraction

TPL abstracts away low-level details of thread management, making it easier to work with concurrency.

Efficient Resource Utilization

TPL efficiently manages threads via the Task Scheduler, which reuses threads from the Thread Pool, reducing resource overhead.

Cancellation

TPL supports graceful cancellation of tasks using CancellationToken, allowing the user to cancel desired tasks.

Asynchronous Programming

Tasks are well-suited for asynchronous programming, allowing non-blocking I/O operations for improved responsiveness.

Parallelism

TPL seamlessly integrates with parallel programming constructs like Parallel.ForEach and PLINQ (Parallel LINQ) to parallelize operations on collections.

Task Continuations

You can define task continuations that specify what to do when a task completes, fails, or is canceled.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Use Cases for TPL

A

Multithreaded computations, where CPU-bound tasks can be parallelized.

Asynchronous I/O operations, such as reading/writing files, making network requests, or database interactions.

Parallel processing of collections using Parallel.ForEach or PLINQ.

Responsive user interfaces that require non-blocking operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

‘Task’ Class

A

TPL (Task Parallel Library)

The “Task” class (System.Threading.Tasks.Task) represents a task (a building block of TPL) which represents an operation (method) that can be executed concurrently & parallelly with other tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Properties of ‘Task’ class

A

public bool IsCompleted { get; }

public TaskStatus Status { get; }

public bool IsFaulted { get; }

public bool IsCanceled { get; }

public AggregateException Exception { get; }

public int Id { get; }

public TResult Result { get; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Methods of ‘Task’ class – Part 1

A

public void Wait()

public bool Wait(int millisecondsTimeout)

public static void WaitAll(params Task[] tasks)

public static int WaitAny(params Task[] tasks)

public Task ContinueWith(Action<Task> continuationAction)</Task>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Methods of ‘Task’ class – Part 2

A

public static Task WhenAll(IEnumerable<Task> tasks)</Task>

public static Task<Task> WhenAny(IEnumerable<Task> tasks)</Task></Task>

public static Task<TResult> FromResult(TResult result)</TResult>

public static Task Delay(int millisecondsDelay)

public static Task FromException(Exception exception)

public static Task Run(Action action)

public static Task<TResult> Run(Func<TResult> function)</TResult></TResult>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Task.Run

A

public static Task Run(Action action)

It is used to create a task. It submits the given method reference to the ‘Task Scheduler’, which leads to create & run the task.

It creates an returns an object of “Task” type.

‘Action’ delegate: The method / lambda expression should receive NO arguments and NO return value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Stopwatch

A

‘Stopwatch’ class

The “Stopwatch” class (System.Diagnostics.Stopwatch) provides functionality for measuring time intervals with high precision.

It is used measure the execution time of a block of code or the performance of a specific operation.

Properties of ‘Stopwatch’ class

bool IsRunning { get; }

Property that indicates whether the stopwatch is currently running.

long ElapsedMilliseconds { get; }

Property that returns the total elapsed time in milliseconds

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Methods of ‘Stopwatch’ class

A

void Start()

Method that starts or resumes the stopwatch.

void Stop()

Method that stops or pauses the stopwatch.

void Reset()

Method that resets the stopwatch, clearing any recorded time.

void Restart()

Method that combines the functions of both Reset() and Start(), resetting the stopwatch and immediately starting a new measurement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Task.Factory.StartNew( )

A

public Task StartNew(Action action)

It is used to create a task. It submits the given method reference to the ‘Task Scheduler’, which leads to create & run the task.

It creates an returns an object of “Task” type.

‘Action’ delegate: The method / lambda expression should receive NO arguments and NO return value.

public Task StartNew(Action action,

CancellationToken cancellationToken,

TaskCreationOptions creationOptions,

TaskScheduler scheduler)

It also creates a new task and creates an object of “Task” type and returns the same, much like StartNew(Action action) method.

This overload of the method can specify custom value for CancellationToken, TaskCreationOptions and custom TaskScheduler.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Task.Wait( )

A

public void Wait()

This method is used to block the current thread until the task on which the method is called completes its execution.

It is similar to “Thread.Join()” method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Task<TResult></TResult>

A

public class Task<TResult> : Task</TResult>

It is a generic class that represents an asynchronous operation much like “Task” class; but the Task<TResult> class can produce a result of type TResult.</TResult>

It inherits the “Task” class; so it contains all properties & methods of “Task” class.

17
Q

Task.WaitAll( )

A

public static void WaitAll(params Task[] tasks)

This method is used to block the current thread, waiting for the completion of multiple tasks before proceeding with further execution.

It is logically equivalent to calling “Task.Wait()” method on each task.

18
Q

Task.WaitAny( )

A

public static int WaitAny(params Task[] tasks)

This method is used to block the current thread, waiting for the completion of any one of the specified tasks before proceeding.

19
Q

Task.Delay( )

A

public static Task Delay(int millisecondsDelay)

This method is used make a delay or pause in the execution of tasks without blocking the calling thread.

It is similar to Thread.Sleep() method in Threading.

It doesn’t pause the current task; but instead, it creates and returns a new “Task” object.

public Task ContinueWith(Action<Task> continuationTask)</Task>

This method schedules a “continuation task” to run when the “original task” is completed (either successfully or with an exception).

It creates an returns an object of “Task” class that represents the continuation task.

The continuation task can read result or exception of the original task.

20
Q

Task Exception Handling

A

Properties of ‘Task’ class

public AggregateException Exception { get; }

Gets the exception that caused the task to fault (if any).

It is null if the task completed successfully or wasn’t faulted

21
Q

Properties of ‘Task’ class

A

public TaskStatus Status { get; }

Gets the current status of the task; any one of the following values.

  1. WaitingForActivation

The task is created but hasn’t started executing yet.

It is waiting to be scheduled by the task scheduler.

  1. WaitingToRun

The task is scheduled to run but is waiting for its turn to be executed by the task scheduler.

public TaskStatus Status { get; }

Gets the current status of the task; any one of the following values.

  1. Running

The task is currently executing its code. It’s actively running.

  1. RanToCompletion

The task has completed successfully without any exceptions.

It has reached to end of the task method successfully.

public TaskStatus Status { get; }

Gets the current status of the task; any one of the following values.

  1. Faulted

The task completed with an unhandled exception.

This indicates that an error occurred during the execution of the task.

  1. Canceled

The task was canceled using the CancellationToken.

22
Q

Task Cancellation

A

Task cancellation is a process that allows you to gracefully cancel the execution of one or more tasks.

Initially, the caller task creates a “cancellation token” and associates the same with the task.

Subsequently, the caller task can cancel the task using the same “cancellation token”.

23
Q

Introduction to Asynchronous Programming

A

Asynchronous programming is a programming paradigm that allows tasks to be executed independently and concurrently, without blocking the main thread of execution.

Non-Blocking I/O operations: The asynchronous read / write operations with external resources such as files, databases or network requests that do not block the current (caller) thread.

24
Q

‘async’ and ‘await’

A

‘async’ Keyword

The ‘async’ keyword is used to make a method, lambda expression or anonymous method as ‘asynchronous method’.

The return type of an async method is typically Task or Task<T> where T is the type of the result (actual return value).</T>

The asynchronous method can be called with ‘await’ keyword.

‘await’ Keyword

The ‘await’ keyword indicates a point where the method should pause its execution and wait for result of an asynchronous method; and also it yields the ‘execution control’ back to its caller until the awaited asynchronous method is complete.

The ‘await’ keyword can only be used within another asynchronous method.

25
Q

How ‘async’ and ‘await’ work?

A
  1. Suspend Execution

When you await an asynchronous operation, the runtime (CLR) suspends the execution of the current method (but not the current thread).

It ensures that the method’s local state is preserved, so when the awaited task completes, the method can resume execution from where it left off.

  1. Continuation

While the awaited task is running asynchronously (e.g., making a network request or reading a file or a database call), the current thread is freed up to perform other work. The method doesn’t block, making your program responsive.

  1. Completion Notification

When the awaited task completes, whether successfully or with an exception, the runtime captures the result or exception information and the caller method resumes execution at the point where it was suspended, and assigns the return value of the asynchronous method at the place where the asynchronous method was called; and then it continues execution of the caller method.

  1. Error Handling

If the awaited task throws an exception, that exception is propagated up the call stack, allowing you to handle errors using standard exception handling mechanisms

26
Q

‘async’ and ‘await’ - Best Practices

A

Avoid “async void”

Avoid using async void methods, especially in top-level event handlers or constructors.

Async void methods can’t be awaited and can make it difficult to catch the unhandled exceptions.

Return Task or Task<TResult></TResult>

Make sure the return of asynchronous methods be either Task (equivalent to void) or Task<TResult> (equivalent to returning TResult).</TResult>

Handle Exceptions Properly

Always handle exceptions that might occur in async methods.

Use try-catch blocks to catch and handle exceptions appropriately.

If an exception is unhandled in an async method, it can crash your application.

Use async/await for I/O-Bound Operations

Async and await are best suited for I/O-bound operations, such as file I/O, network requests or database queries. There is no performance benefit in case of async/await with CPU-bound operations.

Async All the Way

When you have an asynchronous method, make sure to propagate the asynchrony all the way up the call stack.

Avoid using Task.Run() in asynchronous method

Avoid using Task.Run to offload synchronous work to a background thread within an async method.

This can lead to thread pool exhaustion and decreased performance. Instead, use “await”.

Use CancellationToken for Cancellation

Pass a CancellationToken to your async methods when cancellation is possible. This allows you to cancel long-running tasks gracefully.

Be sure to check for cancellation periodically within your async method.

Measure and Optimize

Profile your asynchronous code to identify performance bottlenecks and areas that can be optimized.

Tools like Stopwatch and Visual Studio’s Diagnostic Tools can help you identify and address performance issues.