Calling a call synchronization method from Async Callback?

What happens when a synchronous method is called in an asynchronous callback?

Example:

private void AcceptCallback(IAsyncResult AR) { tcp.BeginReceive(ReceiveCallback); } private void ReceiveCallback(IAsyncResult AR) { tcp.Send(data); } 

The connection will be accepted and the asynchronous receive callback will begin. When a tcp connection receives data, it calls a receive callback.

If you call the send method with synchronization, does this stop other asynchronous callbacks?
Or are all asynchronous callbacks independent of each other?

+5
source share
2 answers

Callbacks are independent because they are called on the thread I / O work starts.

If you're interested, you can see this in the source code . This particular method is for the Socket class (which TcpClient and UdpClient are used internally), where overlapping IO is used to call the callback (see Comment on top of asyncResult.SetUnmanagedStructures invocation:

 private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult) { EndPoint oldEndPoint = m_RightEndPoint; SocketError errorCode = SocketError.SocketError; try { // Set up asyncResult for overlapped WSARecvFrom. // This call will use completion ports on WinNT and Overlapped IO on Win9x. asyncResult.SetUnmanagedStructures( buffer, offset, size, socketAddress, true /* pin remoteEP*/, ref Caches.ReceiveOverlappedCache); asyncResult.SocketAddressOriginal = endPointSnapshot.Serialize(); if (m_RightEndPoint == null) { m_RightEndPoint = endPointSnapshot; } int bytesTransferred; errorCode = UnsafeNclNativeMethods.OSSOCK.WSARecvFrom( m_Handle, ref asyncResult.m_SingleBuffer, 1, out bytesTransferred, ref socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.GetSocketAddressSizePtr(), asyncResult.OverlappedHandle, IntPtr.Zero ); if (errorCode!=SocketError.Success) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } } catch (ObjectDisposedException) { m_RightEndPoint = oldEndPoint; throw; } finally { errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode); } } 
+2
source

Yes, callbacks are independent of each other. They run in the thread pool. There is nothing wrong with that. Mixed synchronization and asynchronous I / O are great. You can use async IO in those places where it gives you the most benefit (places with a large volume with a long wait time).

Remember to call EndReceive.

Also note that the APM pattern is deprecated due to await . You should probably switch.

+2
source

All Articles