2

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) ?

Roman Ratskey
  • 5,101
  • 8
  • 44
  • 67
  • What did you see when you printed `Thread.CurrentThread.ManagedThreadId` ? – L.B Mar 06 '14 at 19:35
  • You don't need to use pool threads explicitly. You can do the processing on the same thread your `BeginReceive`-callback gets invoked on, it's going to be a random but different pool thread. Check the comments to this answer: http://stackoverflow.com/a/22017432/1768303 – noseratio Mar 06 '14 at 22:37

1 Answers1

1

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • i don't wanna do the callbacks on new threads, what i want to do is handle every accepted Socket on a different thread (including all of it's callbacks) – Roman Ratskey Mar 06 '14 at 19:40
  • see my updated topic for another strange manner (see the comments inside the code) – Roman Ratskey Mar 06 '14 at 19:40
  • yea that is useful however i want to handle every connection on a separate thread because inside my custom classbacks OnClientConnect and OnClientExchange etc... i am using synchronous code for some operations and when i do so without the ThreadPool i get all the server as well as the console application to hang up idk why ? – Roman Ratskey Mar 06 '14 at 20:03
  • I have no idea and it seems to be out of scope for this question. You can mix sync and async IO. That should work. The bug is something else. Open a new question and post code. – usr Mar 07 '14 at 11:47