Console Application (VBThreadingBasic)


This example demonstrates how to create threads using VB.NET in three different approaches. And it also shows how to create a thread that requires a parameter. In the target threads, it also shows how to use lock keyword to ensure a code snippet executed without interruption.  A process can create one or more threads to execute a portion of the program code associated with the process. Use a ThreadStart delegate or the ParameterizedThreadStart delegate to specify the program code executed by a thread. The ParameterizedThreadStart delegate allows you to pass data to the thread procedure. The .NET Framework provides us with the System.Threading namespace, which includes the ThreadPool class. This is a static class that you can access directly. It provides us with the essential parts of thread pools. It is an implementation of the common "thread pool" design pattern. It is useful for running many separate tasks in the background. QueueUserWorkItem  function queues a work item to a worker thread in the thread pool. If a function in a DLL is queued to a worker thread, be sure that the function has completed execution before the DLL is unloaded.

By default, the thread pool has a maximum of 512 threads per process. To raise the queue limit, use the WT_SET_MAX_THREADPOOL_THREAD macro defined in WinNT.h.

Running the Sample

Using the Code

1. Create a thread by new Thread object.

Dim ts1 As New ThreadStart(AddressOf ThreadFunction1)
Dim t1 As New Thread(ts1)


2. Create a thread by ThreadPool.QueueUserWorkItem.

ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ThreadFunction2))


3. Create a thread by ThreadStart.BeginInvoke.

Dim ts2 As New ThreadStart(AddressOf ThreadFunction3)
ts2.BeginInvoke(Nothing, Nothing)


4. Create a thread with parameters.

Dim pts As New ParameterizedThreadStart(AddressOf ThreadFunction4)
Dim t2 As New Thread(pts)


More Information

C# Threading Programming Guid.

Thread Class document.