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

  • SEARCH
  • Home
  • 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 8636199
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T10:10:22+00:00 2026-06-12T10:10:22+00:00

How to prevent this issue when writing data to the client Asynchronously The BeginWrite

  • 0

How to prevent this issue when writing data to the client Asynchronously

The BeginWrite method cannot be called when another write operation is pending

MYCODE

public async void Send(byte[] buffer)
{
    if (buffer == null)
        return;
    await SslStream.WriteAsync(buffer, 0, buffer.Length);
}
  • 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-06-12T10:10:24+00:00Added an answer on June 12, 2026 at 10:10 am

    It is important to understand exactly what the await keyword does:

    An await expression does not block the thread on which it is
    executing. Instead, it causes the compiler to sign up the rest of the
    async method as a continuation on the awaited task. Control then
    returns to the caller of the async method. When the task completes, it
    invokes its continuation, and execution of the async method resumes
    where it left off (MSDN – await (C# Reference)).

    When you call Send with some non null buffer you will get to

        await SslStream.WriteAsync(buffer, 0, buffer.Length);
    

    Using await you block the execution only in the Send method, but the code in the caller continues to execute even if the WriteAsync has not completed yet. Now if the Send method is called again before the WriteAsync has completed you will get the exception that you have posted since SslStream does not allow multiple write operations and the code that you have posted does not prevent this from happening.

    If you want to make sure that the previous BeginWrite has completed you have to change the Send method to return a Task

        async Task Send(SslStream sslStream, byte[] buffer)
        {
            if (buffer == null)
                return;
    
            await sslStream.WriteAsync(buffer, 0, buffer.Length);
        }
    

    and wait for it’s completion by calling it using await like:

        await Send(sslStream, message);
    

    This should work if you do not attempt to write data from multiple threads.

    Also here is some code that prevents write operations from multiple threads to overlap (if properly integrated with your code). It uses an intermediary queue and the Asynchronous Programming Model(APM) and works quite fast.
    You need to call EnqueueDataForWrite to send the data.

        ConcurrentQueue<byte[]> writePendingData = new ConcurrentQueue<byte[]>();
        bool sendingData = false;
    
        void EnqueueDataForWrite(SslStream sslStream, byte[] buffer)
        {
            if (buffer == null)
                return;
    
            writePendingData.Enqueue(buffer);
    
            lock (writePendingData)
            {
                if (sendingData)
                {
                    return;
                }
                else
                {
                    sendingData = true;
                }
            }
    
            Write(sslStream);            
        }
    
        void Write(SslStream sslStream)
        {
            byte[] buffer = null;
            try
            {
                if (writePendingData.Count > 0 && writePendingData.TryDequeue(out buffer))
                {
                    sslStream.BeginWrite(buffer, 0, buffer.Length, WriteCallback, sslStream);
                }
                else
                {
                    lock (writePendingData)
                    {
                        sendingData = false;
                    }
                }
            }
            catch (Exception ex)
            {
                // handle exception then
                lock (writePendingData)
                {
                    sendingData = false;
                }
            }            
        }
    
        void WriteCallback(IAsyncResult ar)
        {
            SslStream sslStream = (SslStream)ar.AsyncState;
            try
            {
                sslStream.EndWrite(ar);
            }
            catch (Exception ex)
            {
                // handle exception                
            }
    
            Write(sslStream);
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing a modular project in Rails3, and I've this issue. I've my main
Can someone advice me how to prevent this error. An item with the same
We are running a test automation suite and would like to prevent this message
The trigger below is delaying my insert response. How can I prevent this? create
JBoss crashed with out of memory error, how do I prevent this? I modified
This popup prevent other scripts from running and prints the following: instruments[2596] : kCGErrorInvalidConnection:
In this question I learned how to prevent the insert of a NULL value.
this Question moved to how to prevent an Gated Check-In to put the Keyword
I'm trying to do this in a way that will prevent end-user browser security
I'm looking to prevent session hijacking in my ASP.NET application and came across this

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.