ThreadPool.QueueUserWorkItem Method (WaitCallback)
Queues a method for execution. The method executes when a thread pool thread becomes available.
Assembly: mscorlib (in mscorlib.dll)
'Declaration Public Shared Function QueueUserWorkItem ( _ callBack As WaitCallback _ ) As Boolean
You can place data required by the queued method in the instance fields of the class in which the method is defined, or you can use the QueueUserWorkItem(WaitCallback, Object) overload that accepts an object containing the necessary data.
Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor.
The following example uses the method overload to queue a task, which is represented by the ThreadProc method, to execute when a thread becomes available. No task information is supplied with this overload. Therefore, the information that is available to the ThreadProc method is limited to the object the method belongs to.
Imports System Imports System.Threading Public Class Example <MTAThread> _ Public Shared Sub Main() ' Queue the task. ThreadPool.QueueUserWorkItem( _ New WaitCallback(AddressOf ThreadProc) _ ) ' Note that you do not have to create the WaitCallback delegate ' explicitly in Visual Basic. The following line also queues ' the task: 'ThreadPool.QueueUserWorkItem(AddressOf ThreadProc) Console.WriteLine("Main thread does some work, then sleeps.") ' If you comment out the Sleep, the main thread exits before ' the thread pool task runs. The thread pool uses background ' threads, which do not keep the application running. (This ' is a simple example of a race condition.) Thread.Sleep(1000) Console.WriteLine("Main thread exits.") End Sub ' This thread procedure performs the task. Shared Sub ThreadProc(stateInfo As Object) ' No state object was passed to QueueUserWorkItem, so ' stateInfo is null. Console.WriteLine("Hello from the thread pool.") End Sub End Class
Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.