views:

362

answers:

1

I have written an async UDP client to talk to a server at my company. When I run on my developer machine all is well. When I deploy to another machine I get a socket exception on EndReceive the first time I send data over the socket. My dev box is Win7 and I have deployed to both an XP SP3 machine and a Server 2003 R2 machine. Below is the receive code:

Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
    Try
        ' Retrieve the state object and the client socket 
         from the asynchronous state object.'

        Dim state As StateObj = CType(ar.AsyncState, StateObj)
        Dim client As Socket = state.sockArg

        ' Read data from the remote device.'
        Dim bytesRead As Integer
        receiveDone.WaitOne(Timeout.Infinite)

        bytesRead = client.EndReceive(ar)
        If bytesRead > 0 Then
            Dim s As String = Encoding.ASCII.GetString(state.buffer, 0, bytesRead)
            parsedata(s)
        End If
    Catch SockEx As SocketException
        mlog.Error(String.Format("ID={1} {0} SocketError={2}", SockEx.Message, ID.ToString, SockEx.SocketErrorCode.ToString), SockEx)
    Catch ox As System.ObjectDisposedException
        mlog.Warn(String.Format("Object Disposed ID={0}", ID.ToString))
    Catch ex As Exception
        mlog.Error(String.Format("{1} ID={0}", ID.ToString, ex.Message), ex)
    End Try
End Sub 'ReceiveCallback

The exception I get is:

System.Net.Sockets.SocketException: The I/O operation has been aborted because of either a thread exit or an application request at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at RTSPc.Connection.ReceiveCallback(IAsyncResult ar)

The SocketException is OperationAborted

+3  A: 

It's likely that the reason that it doesn't fail on your dev box is that the underlying behaviour of the I/O system was changed in Vista so that overlapped I/O that was issued by a thread is no longer cancelled when the thread exits.

See this posting on my blog about this: http://www.lenholgate.com/archives/000763.html

Now, why you're getting the problem on XP is the real question and to answer that we'd probably need to know a little more about how you're issuing your overlapped I/O requests and from where. Are you running any threads of your own? Do they issue any I/O requests?

Len Holgate
Your blog post pointed me in the right direction. I was calling the class from a separate thread that finished right after calling send on the socket. Thank you.
jercra
Cool, I expected it to be something like that. It's a pity that the .Net Async I/O stuff didn't abstract away the messy nature of pre-Vista I/O cancelling; Richter suggests not allowing threads with outstanding I/O to exit at all, my approach was to marshal the actual I/O request into a thread pool that was under my control and which never let its threads die.
Len Holgate