Roman Ratskey
Roman Ratskey

Reputation: 5259

Using ThreadPool With Callbacks

I am using ThreadPool to handle every connected Socket in my Socket Server separately. However i wonder if the callback of BeginReceive also gets execute inside the ThreadPool

ThreadPool.QueueUserWorkItem(o =>
{
    if (ClientExchange != null && ClientExchange(asynchronousState)) {
        if (ClientConnect != null) {
            ClientConnect(asynchronousState);
        }
    }
    ConnectedClients.Add(ipEndPoint, socket);
    socket.BeginReceive(asynchronousState.Buffer, 0, asynchronousState.Buffer.Length, SocketFlags.None, HandleAsyncReceive, asynchronousState);
});

Does the HandleAsyncReceive callback gets also executed in the new Thread (which was grabbed by the ThreadPool) ?

Upvotes: 2

Views: 997

Answers (1)

usr
usr

Reputation: 171178

Callbacks for async IO are called on thread-pool threads.

Thread-pool threads are never reserved for any specific purpose. Every work item can see a totally different thread-id. Or all work items could see the same thread-id. Nothing is guaranteed.

Normally, you don't rely on the exact thread that your code will run on. This is usually a bug. You should not care about this (and I'm unclear why you do).

what i want to do is handle every accepted Socket on a different thread

That does not make sense in the context of async IO. Async IO is thread-less. While an IO is running there is no thread in use for it.

Upvotes: 1

Related Questions