Use the Thread Object with a Task That Returns Data

Problem

You want to execute a task on a separate thread, and you want to retrieve the data it produces.

Solution

Create a custom threaded class that incorporates a parameterless method, along with a method or property to retrieve the information. In addition, you might want to use an event to notify the caller.

Discussion

When you create a Thread object, you must supply a delegate that points to a method without a return value. This limits your ability to retrieve information from the thread once its work is complete. The easiest solution is to wrap the threaded code and the return value into a single class. You can then add methods that allow the main application thread to retrieve the return value ...

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.