0

In the example of Socket.BeginReceive() your provided method will be called from a thread-pool thread when the asynchronous operation completes. The assumed behaviour seems to be that you will handle the callback and return, typically having called another async method.

But one could use this as a way to obtain a thread which you then use to manage that socket. Is retaining/monopolising this thread (does this have a proper name) going to cause problems or is it just another worker thread you can use as you want?

Note: I'm aware this isn't the modern paradigm for using Sockets and doesn't scale well

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • https://stackoverflow.com/questions/21015746/does-c-sharp-asynccallback-creates-a-new-thread – CodeCaster Jan 13 '20 at 15:11
  • @CodeCaster I'm not sure how this answers my question, could you elaborate? – Mr. Boy Jan 13 '20 at 15:15
  • It's unlikely to cause an issue in practice, but in theory you could starve the thread pool of all its threads. If you exceed `ThreadPool.GetMinThreads()` number of threads, a delay will be introduced between each new thread being created. If you exceed `ThreadPool.GetMaxThreads()` then the thread attempting to create a new thread will block until another threadpool thread is returned to the scheduler. This is A Bad Thing. – Matthew Watson Jan 13 '20 at 15:19
  • 1
    I don't know C#, but it sounds like this is a specific question about `Socket.BeginReceive()`, and not a question about thread pools in general. A different library routine might have different expectations about what is OK or not OK for you to do in some callback function that you provide. You might want to change the question title. – Solomon Slow Jan 13 '20 at 15:20
  • [Socket.BeginReceive](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.beginreceive?view=netframework-4.8) documentation says that `The asynchronous BeginReceive operation must be completed by calling the EndReceive method. Typically, the method is invoked by the callback delegate.` So socket is being managed somehow in the `callback` procedure.Calling `BeginReceive` to get one more running thread looks strange but why not? – oleksa Jan 13 '20 at 15:22
  • AFAIK, it must be an IOCP thread and not threadpool / worker thread. These are two set of thread pools unless someone like to correct me. – S.N Jan 13 '20 at 15:27
  • @SolomonSlow I'm not sure I quite agree but given oleksa's detail I think you're right. I've edited – Mr. Boy Jan 13 '20 at 15:27

0 Answers0