ThreadPool..::.QueueUserWorkItem Method (WaitCallback)
This page is specific to:.NET Framework Version:2.03.03.5Silverlight 34.0
.NET Framework Class Library
ThreadPool..::.QueueUserWorkItem Method (WaitCallback)

Queues a method for execution. The method executes when a thread pool thread becomes available.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Syntax

'Usage

Dim callBack As WaitCallback
Dim returnValue As Boolean

returnValue = ThreadPool.QueueUserWorkItem(callBack)

'Declaration

Public Shared Function QueueUserWorkItem ( _
    callBack As WaitCallback _
) As Boolean

Parameters

callBack
Type: System.Threading..::.WaitCallback
A WaitCallback that represents the method to be executed.

Return Value

Type: System..::.Boolean
true if the method is successfully queued; NotSupportedException is thrown if the work item is not queued.
Exceptions

ExceptionCondition
NotSupportedException

The common language runtime (CLR) is hosted, and the host does not support this action.

ArgumentNullException

callBack is nullNothingnullptra null reference (Nothing in Visual Basic).

Remarks

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.

NoteNote:

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.

Version Information

In the .NET Framework version 2.0, the Thread..::.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

Examples

The following example uses the QueueUserWorkItem(WaitCallback) 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


Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Community Content

Remember to Handle Exceptions
Added by:LukeSkywalker

Buried deep in the documentation is the fact that unhandled exceptions in threadpool threads close the process entirely. You may find that the debugger catches them during testing but that release code simply closes the app - ASP.NET or WCF apps closing may not be as noticeable.

"Unhandled exceptions on thread pool threads terminate the process." from http://msdn.microsoft.com/en-us/library/0ka9477y.aspx

You may be interested in the AppDomain.UnhandledException event which could be useful...

http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Also, the compiler-generated BeginInvoke methods on delegates might be affected as rumour has it that these are spun up on ThreadPool threads. See http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

Neater code through Lambda expressions
Added by:LukeSkywalker

The WaitCallback is not necessary since Lambdas and delegates came along. Also note that this method is de-emphasised in CLR 4.0 in favor of Tasks.

System.Threading.ThreadPool.QueueUserWorkItem(state => {
try
{
WorkerClass.PerformCostlyOp(state);
}
catch(Exception e)
{
// You could react or save the exception to an 'outside' variable // threadExc = e;
}
finally
{
resetEvent.Set(); // if you're firing and not forgetting ;)
}

}, myState);
if (!ManualResetEvent.WaitOne(resetEvent, 1000)) { throw TimeoutException("Waited ages for a thread to come in."); }
if (threadExc != null) { throw threadExc; }

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View