private void WriteHeader(NetworkStream stream)
        {
            batchesSent++;

            if (batchesSent > TotalBatches)
            {
                //Mark end of transfer.
                byte[] b = new byte[sizeof(long)];
                b = BitConverter.GetBytes((long)0);
                stream.Write(b, 0, sizeof(long));
                sendDone.Set();
                return;
            }

            Log.LogMessage("Sending request " + batchesSent.ToString());

            TcpClient2OutputStreamContext ctx = new TcpClient2OutputStreamContext();
            ctx.OutputStream = new MemoryStream();
            ctx.ClientStream = stream;
            StreamUtil.GenerateBigRequest(ctx.OutputStream, false, recordCount, recordCount + (BatchSize - 1));
            ctx.OutputStream.Seek(0, SeekOrigin.Begin);

            byte[] header = BitConverter.GetBytes(ctx.OutputStream.Length);
            stream.BeginWrite(header, 0, header.Length, BeginWriteCallback, ctx);

            recordCount += BatchSize;
        }
        private void WriteHeader(NetworkStream stream)
        {
            batchesSent++;

            if (batchesSent > TotalBatches)
            {
                //Mark end of transfer.
                byte[] b = new byte[sizeof(long)];
                b = BitConverter.GetBytes((long)0);
                stream.Write(b, 0, sizeof(long));
                sendDone.Set();
                return;
            }

            Log.LogMessage("Sending request " + batchesSent.ToString());

            TcpClient2OutputStreamContext ctx = new TcpClient2OutputStreamContext();
            ctx.OutputStream = new MemoryStream();
            ctx.ClientStream = stream;
            StreamUtil.GenerateBigRequest(ctx.OutputStream, false, recordCount, recordCount + (BatchSize - 1));
            ctx.OutputStream.Seek(0, SeekOrigin.Begin);

            byte[] header = BitConverter.GetBytes(ctx.OutputStream.Length);
            Log.LogMessage("Sending header: " + ctx.OutputStream.Length.ToString() + " header length: " + header.Length.ToString());

            Task.Factory.FromAsync<byte[], int, int>(stream.BeginWrite, stream.EndWrite, header, 0, header.Length, ctx).ContinueWith(BeginWriteCallback).ContinueWith(TaskExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);

            recordCount += BatchSize;
        }