There are many uses for the ThreadPool class. One such use is when I want to send an
object (service/data) to a server over the network. By using the ThreadPool::QueueUserWorkItem() method
you queue the service and data in its own thread and allocate a delegate to handle the
task.
Assumimg you have created such an object ready to send, you can start the process by
calling ThreadPool::QueueUserWorkItem(). The object is assumed to be derived from a class that
implements functionality to enable communication with a server, such as Send(), OnServerResponse(),
Connect(), Wait(), etc...
static bool _InProgress = true;
SomeClass ^ obj = gcnew SomeClass();
// optionally set a delegate to handle callback from the server. For example,
obj->OnServerResponse(gcnew OnServerResponseCallback(this, &MyNamespace::MyClass::HandleServerResponse);
// Queue the service and data.
System::Threading::ThreadPool::QueueUserWorkItem(gcnew WaitCallback(this, &MyNamespace::MyClass::MyProcedure), obj);
// If some kind of 'OnServerClosed' callback is available, handle timeout.
while (true)
{
DateTime start = DateTime::Now;
if (_InProgress){ //
TimeSpan span = DateTime::Now - start;
if (span.TotalMinutes > 10){ // 10 minutes
throw gcnew System::Exception("obj hang for more than 10 minutes");
}
}
else { // _InProgress set to false by optional OnServerClosed callback
break;
}
Thread::Sleep(3000);
}
Elsewhere in the class you implement the MyProcedure() method, which will connect to the server.
public: void MyProcedure(System::Object ^state)
{
SomeClass^ obj = dynamic_cast<SomeClass^>(state);
// assuming this object has a method to connect to a server
obj->Connect(SomeConfig::RemoteHost, SomeConfig::RemotePort, SomeSocketType::TCP);
if (!obj->Wait()) { // server error or unavailable
String^ message = String::Format("Error: {0}", obj->ErrorMessage);
System::Diagnostics::Debug::WriteLine(message);
}
}