Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 413661
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T18:12:22+00:00 2026-05-12T18:12:22+00:00

I’ve been having this issue for a while now and was never really able

  • 0

I’ve been having this issue for a while now and was never really able to resolve it. This issue only appears when I’m using the SendAsync/ReceiveAsync methods rather than the Begin/EndSend socket methods for asynchronous operations.

If have a fairly sophisticated tcp socket library and been meaning to replace the BeginSend methods with SendAsync but because of the issue I’m experiencing I always had to put it off. My socket server is handling heavy stress scenarios with > 1000 clients connected pushing constantly over 100mbit/sec and I’d like to utilize SendAsync method so I don’t have the IAsyncResult allocation overhead.

Anyways, what happens is, everything works fine as long as I’m just sending/receiving data, however under high stress scenarios when the server is trying to disconnect/shutdown a client I’m occasionally getting the following Exception:

    System.InvalidOperationException was unhandled
  Message=Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call.
  Source=mscorlib
  StackTrace:
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
       at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
       at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
  InnerException: 

I’m unable to catch this exception anywhere as it seems to happen within the .NET framework and I can’t do anything about it crashing my server.

As this only happens when I call my shutdown procedure, I’m guessing it has something to do with calling Shutdown on the socket while it still has a Read/Write procedure pending.
However, I also tried to delay calling shutdown until all read/write Send/ReceiveAsync calls have returned and call shutdown after that but that didn’t help either.

Here’s how I try to shutdown sockets:

        private void InternalDisconnect(SocketError socketError)
    {
        lock (shutdownLock)
        {
            if (isShutdown)
                return;

            isShutdown = true;
        }

        allowSend = false;
        SocketError = socketError;

        ThreadPool.QueueUserWorkItem(delegate
                                         {
                                             lock (padLock)
                                             {
                                                 try
                                                 {
                                                     if (TcpSocketStatus == TcpSocketStatus.Disconnected)
                                                         return;

                                                     TcpSocketStatus = TcpSocketStatus.Disconnecting;

                                                     if (asyncSendArgs != null)
                                                     {
                                                         asyncSendArgs.Completed -= SendCompleted;
                                                         asyncSendArgs.SetBuffer(null, 0, 0);
                                                         asyncSendArgs.Dispose();
                                                     }

                                                     if (asyncReceiveArgs != null)
                                                     {
                                                         asyncReceiveArgs.Completed -= ReceiveCompleted;
                                                         asyncReceiveArgs.SetBuffer(null, 0, 0);
                                                         asyncReceiveArgs.Dispose();
                                                     }

                                                     try
                                                     {
                                                         bufferedSender.Clear();

                                                         Socket.Shutdown(SocketShutdown.Both);

                                                         if (Socket.Connected)
                                                         {
                                                             Socket.Disconnect(true);
                                                         }
                                                     }
                                                     catch
                                                     {
                                                     }

                                                     try
                                                     {
                                                         Socket.Close();
                                                     }
                                                     catch
                                                     {
                                                     }

                                                     TcpSocketStatus = TcpSocketStatus.Disconnected;

                                                     if (socketError != SocketError.Success)
                                                     {
                                                         if (log.IsDebugEnabled)
                                                             log.Debug("SocketDisconnected\tSocketError:{0}", socketError);
                                                     }
                                                     else
                                                     {
                                                         if (log.IsDebugEnabled)
                                                             log.Debug("SocketDisconnected");
                                                     }

                                                     DisconnectTime = DateTime.UtcNow;

                                                     if (TcpSocketDisconnected != null)
                                                         TcpSocketDisconnected(this);
                                                 }
                                                 catch (Exception ex)
                                                 {
                                                     log.ErrorException("InternalDisconnect", ex);
                                                 }
                                             }
                                         });
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T18:12:22+00:00Added an answer on May 12, 2026 at 6:12 pm

    Ok, for some reason it always helps me to ask question because I tend to figure out things always shortly after :/

    It seems that asyncSendArgs.SetBuffer(null, 0, 0); is the culprit.
    Even though that another piece of the code should make sure that there are no outstanding async operations before InternalDisconnect is called it seems like there still are and altering the buffer while it’s in use would definitely cause an issue.
    I’ve been running heavy stress tests for 15 minutes so far and everything seems fine (before I always got that exception within one minute). I’ll let it run for some more time and hope that that did it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 196k
  • Answers 196k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer It's exactly the same in Windows. i.e ping google.com >… May 12, 2026 at 7:10 pm
  • Editorial Team
    Editorial Team added an answer I can recommend this tutorial by Dustin Yoniak. It shows… May 12, 2026 at 7:10 pm
  • Editorial Team
    Editorial Team added an answer A few tips: Load sIFR CSS & JavaScript first Minimize… May 12, 2026 at 7:10 pm

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a French site that I want to parse, but am running into
I have text I am displaying in SIlverlight that is coming from a CMS
I am currently running into a problem where an element is coming back from

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.