Use the Thread Object with a Task That Requires Data

Problem

You want to execute a task on a separate thread, and you need to supply certain input parameters.

Solution

Create a custom threaded class that incorporates a parameterless method, along with the additional information as member variables.

Discussion

When you create a Thread object, you must supply a delegate that points to a method without parameters. This causes a problem if you need to pass information to the thread. The easiest solution is to wrap the threaded code and the required information into a single class.

Consider the example where you want to write a large amount of information to a file in the background. You can encapsulate this logic in the task class shown here:

Public Class ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.