We help IT Professionals succeed at work.

How to cancel a pending BeginReceive method of Socket class in .NET without using Close method ?

kalibuk asked
How to cancel a pending BeginReceive method of Socket class in .NET without using Close method ?
Watch Question


Any help appreciated.
Hi Kalibuk,  do you any code written yet? Can you post it?  Is this a general inquiry or do you have a specific situation or bug that you are trying overcome?


From my code I call attached function WaitForData(). When the caller decides to not wait any more, the callback OnDataReceived is still hanging in memory. Proper solution is to call Close() method on ((Socket)objResource), but I cannot lost handle to the opened socket or create another one.
private int WaitForData()
                if (pfnCallBack == null)
                    pfnCallBack = new AsyncCallback(OnDataReceived);
                // now start to listen for any data...
                m_asynResult =
                ((Socket)objResource).BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
                return NTRESULT.OK;

Open in new window

Just asking so I can understand the situation better:

1. What is the reason you don't want to specify the timeout?

2. What is the reason you can't create another socket?
It seems that the short answer is that you can't:


However, there might be a slightly different way to accomplish your goal. That's why I'm asking the above question.  Just trying to understand what you are trying to do.

I suppose you could abort the thread but I would not design it that way.  Another choice would be to use a non-blocking socket instead of async:

Please disregard the comment about aborting the thread, that won't help and is a very bad idea.


so as you suggested we abandoned idea of async receive while there is no easy way to kill pending method. I rewrote the code to use simple Receive method in blocking mode  and now I'm able to cancel Receive method on custom event I get from caller. So thanks!
Glad I was able to assist - and thanks for asking such an interesting question.