Visual Basic .NET - Task Parallel Library (TPL) in VB.NET

The Task Parallel Library (TPL) is a powerful feature in .NET that simplifies parallel programming by allowing developers to run multiple operations concurrently. Instead of manually creating and managing threads, TPL provides a higher-level abstraction through tasks, which represent asynchronous units of work. This approach improves performance, scalability, and code readability.


1. Concept of Tasks

A Task in VB.NET represents an operation that runs asynchronously. It is part of the System.Threading.Tasks namespace. Tasks are more efficient than traditional threads because they are managed by the .NET thread pool.

For example, instead of creating a thread manually, you can use a task:

Imports System.Threading.Tasks

Module Module1
    Sub Main()
        Dim t As Task = Task.Run(Sub()
                                     Console.WriteLine("Task is running")
                                 End Sub)
        t.Wait()
    End Sub
End Module

In this example, Task.Run executes the code asynchronously using a thread pool thread.


2. Parallel Execution with Parallel Class

The Parallel class provides methods like Parallel.For, Parallel.ForEach, and Parallel.Invoke to execute multiple operations simultaneously.

Parallel.For Example

Imports System.Threading.Tasks

Module Module1
    Sub Main()
        Parallel.For(0, 5, Sub(i)
                               Console.WriteLine("Iteration: " & i)
                           End Sub)
    End Sub
End Module

This runs iterations in parallel, not sequentially, which can significantly improve performance for CPU-bound operations.


3. Parallel.ForEach

This is used to iterate over collections in parallel:

Imports System.Threading.Tasks

Module Module1
    Sub Main()
        Dim numbers = {1, 2, 3, 4, 5}
        Parallel.ForEach(numbers, Sub(num)
                                     Console.WriteLine(num)
                                 End Sub)
    End Sub
End Module

Each element is processed concurrently.


4. Parallel.Invoke

Parallel.Invoke allows multiple independent methods to run at the same time:

Imports System.Threading.Tasks

Module Module1
    Sub Main()
        Parallel.Invoke(
            Sub() Console.WriteLine("Task 1"),
            Sub() Console.WriteLine("Task 2"),
            Sub() Console.WriteLine("Task 3")
        )
    End Sub
End Module

Each delegate runs in parallel.


5. Task Lifecycle

A task goes through different states:

  • Created

  • Waiting to run

  • Running

  • Completed

  • Faulted (if an exception occurs)

  • Canceled

You can monitor task status using properties like IsCompleted, IsFaulted, and Status.


6. Handling Exceptions in Tasks

Exceptions inside tasks do not immediately crash the program. They are stored and can be accessed when the task is awaited or waited upon.

Dim t As Task = Task.Run(Sub()
                             Throw New Exception("Error occurred")
                         End Sub)

Try
    t.Wait()
Catch ex As AggregateException
    For Each e In ex.InnerExceptions
        Console.WriteLine(e.Message)
    Next
End Try

TPL wraps exceptions in AggregateException.


7. Task Continuations

You can define actions that execute after a task completes using ContinueWith:

Dim t As Task = Task.Run(Sub()
                             Console.WriteLine("Main Task")
                         End Sub)

t.ContinueWith(Sub()
                   Console.WriteLine("Continuation Task")
               End Sub)

t.Wait()

This allows chaining operations.


8. Cancellation Support

TPL supports cooperative cancellation using CancellationToken.

Imports System.Threading
Imports System.Threading.Tasks

Dim cts As New CancellationTokenSource()

Dim t As Task = Task.Run(Sub()
                             For i = 1 To 10
                                 If cts.Token.IsCancellationRequested Then
                                     Console.WriteLine("Cancelled")
                                     Exit For
                                 End If
                                 Console.WriteLine(i)
                                 Thread.Sleep(500)
                             Next
                         End Sub, cts.Token)

cts.Cancel()

This allows controlled stopping of tasks.


9. Benefits of TPL

  • Simplifies complex multithreading

  • Improves application performance

  • Efficient use of system resources via thread pooling

  • Better scalability on multi-core processors

  • Built-in support for cancellation and exception handling


10. When to Use TPL

TPL is best suited for:

  • CPU-intensive operations such as calculations or data processing

  • Running independent tasks simultaneously

  • Improving responsiveness in applications

However, it should be used carefully to avoid issues like race conditions, deadlocks, and excessive parallelism.


Conclusion

The Task Parallel Library is a modern and efficient approach to handling concurrency in VB.NET. By abstracting low-level threading details, it enables developers to write clean, scalable, and high-performance applications. Understanding tasks, parallel loops, and synchronization mechanisms is essential to effectively using TPL in real-world scenarios.