title: How to fix deadlock while sending a few MB file via tcp socket?
body: <p>I'd like to send file via raw tcp socket.
  When I send files smaller than defined buffer, it works.
  When I send 10MB files and tcp no delay option is on, server hangs on reading last chunk.
  It never happen when I send that file at once(increasing buffer size).
  Here is my code.</p>
  <p>Client is Xamarin Forms, server is c++/cli.</p>
  <p>I'm thinking of race conditions, deadlocks.</p>
  <p>Client</p>
  <pre><code>private async Task SendBigFile(Stream stream)
          {
                  using (var bw = new BinaryWriter(this.ns, Encoding.UTF8, true))
                  {
                      const int bufferSize = 65535;
                      long bytesLeft = stream.Length;
                      while (bytesLeft &gt; 0)
                      {
                          var dataSize = (int)Math.Min(bytesLeft, bufferSize);
                          var data = new byte[dataSize];
                          var bytesRead = await stream.ReadAsync(data, 0, dataSize);
                          if (bytesRead != 0)
                          {
                              bw.Write(data, 0, bytesRead);
                              bw.Flush();
                              bytesLeft -= bytesRead;
                          }
                          else
                              break;
                  }
          }
  </code></pre>
  <p>Server</p>
  <pre><code>void receiveBigFile(unsigned int length, System::IO::Stream^ stream)
  {
      const System::Int64 bufferSize = 65535;
      System::Int64 bytesLeft = length, bytes = 0;
      System::IO::BinaryReader^ br = nullptr;
      try
      {
          br = gcnew System::IO::BinaryReader(this-&gt;ns, System::Text::Encoding::UTF8, true);
          while (bytesLeft &gt; 0)
          {
                  System::Int32 dataSize = System::Math::Min(bytesLeft, bufferSize);
                  array&lt;System::Byte&gt;^ data = gcnew array&lt;System::Byte&gt;(dataSize);
                  System::Int64 bytesRead = br-&gt;Read(data, 0, data-&gt;Length);
                  if (bytesRead != 0)
                  {
                      stream-&gt;Write(data, 0, bytesRead);
                      bytesLeft -= bytesRead;
                  }
                  else
                      break;
          }
      }
      finally
      {
          if (br != nullptr)
          {
              br-&gt;Close();
          }
      }
  }
  </code></pre>