Console Application (VBThreadingBasic)

Introduction

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.

VB
Edit|Remove
Dim ts1 As New ThreadStart(AddressOf ThreadFunction1)
Dim t1 As New Thread(ts1)
t1.Start()

 

2. Create a thread by ThreadPool.QueueUserWorkItem.

VB
Edit|Remove
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ThreadFunction2))

 

3. Create a thread by ThreadStart.BeginInvoke.

VB
Edit|Remove
Dim ts2 As New ThreadStart(AddressOf ThreadFunction3)
ts2.BeginInvoke(Nothing, Nothing)

 

4. Create a thread with parameters.

VB
Edit|Remove
Dim pts As New ParameterizedThreadStart(AddressOf ThreadFunction4)
Dim t2 As New Thread(pts)
t2.Start("Message")

 

More Information

C# Threading Programming Guid.

http://msdn.microsoft.com/en-us/library/ms173178(VS.80).aspx

Thread Class document.

http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx

ThreadPool.QueueWorkItem.

http://msdn.microsoft.com/en-us/library/kbf0f1ct.aspx