Wednesday, July 22, 2009

WaitCallback method has to be static

The following is a demo for using WaitCallback delegate. Note that the method ThreadProc has to be static.

using namespace System;
using namespace System::Threading;
ref class Example

// This thread procedure performs the task.
static void ThreadProc( Object^ stateInfo )

// No state object was passed to QueueUserWorkItem, so
// stateInfo is 0.
Console::WriteLine( "Hello from the thread pool." );


int main()

// Queue the task.
ThreadPool::QueueUserWorkItem( gcnew WaitCallback( Example::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." );
return 0;

If it's not static, we'll get the following error:
error C3867: 'Example::ThreadProc': function call missing argument list; use '&Example::ThreadProc' to create a pointer to member
error C3350: 'System::Threading::WaitCallback' : a delegate constructor expects 2 argument(s)


1 comment:

Xiaoguang said...

WaitCallback has two constructors.
1. WaitCallback(StaticMethodName)
2. WaitCallback(instanceName, &Instance::InstanceMethodName)