0

I'm wanting to track the state of my upload request, something like :

  • Upload packet
  • Update UI with progress
  • Upload packet
  • Update UI with progress
  • Upload packet
  • Update UI with progress
  • etc etc

So I tried the following code (gathered from examples found online).

void SendData()
{
    byte[] bytes = Encoding.UTF8.GetBytes(GetContent());
    HttpWebRequest webRequest = WebRequest.Create(GetURL()) as HttpWebRequest;
    webRequest.Method = "PUT";
    webRequest.ContentType = @"application/x-www-form-urlencoded";
    webRequest.ContentLength = bytes.Length;

    // this doesn't seem to help
    webRequest.AllowWriteStreamBuffering = false;

    using (Stream reqStream = webRequest.GetRequestStream())
    {
        int bytesUploaded = 0;
        while (bytesUploaded != bytes.Length)
        {
            int packetSize = Math.Min(PACKETSIZE, bytes.Length - bytesUploaded);
            reqStream.Write(bytes /*buffer*/, 
                            bytesUploaded /*Offset*/, 
                            packetSize /*Count*/);

            // this doesn't seem to help
            reqStream.Flush();

            bytesUploaded += packetSize;
            UI.SetProgress(bytesUploaded / bytes.Length, 
                           true /*Dispatch?*/);
        }
    }

    WebResponse webResponse = webRequest.GetResponse(); //stalls here while it uploads
}

but it isn't working as expected. It isn't uploading the bytes after the flush, but instead running through the multiple iterations of the while loop, and then uploading at the GetResponse() stage. I know its not uploading within the while loop because no matter how large I set the byte array, the time taken to go through the loop barely changes; yet the time at the GetResponse() stage increase proportionately.

Resulting in the progress going from 0-100% in the blink of an eye, and then staying at 100% for the time it takes to actually send the data.

Noctis
  • 11,507
  • 3
  • 43
  • 82
pastillman
  • 1,104
  • 2
  • 16
  • 27

1 Answers1

0

First, I can't find the definition of your PACKETSIZE. Did you debug it and made sure that your bytes is longer than the packet size constant?

Second, I doubt you're using that loop correctly. When you're uploading , your GetRequestStream is updated at the end, and trying to flush it midway doesn't seem correct. (Have a look at this answer for more details).

Try this: break the array into 10 pieces. Run a loop from 0-9, and in each send the corresponding array bit, wait for the response, flush/close the stream, then call the UI.SetProgress. Rinse and repeat.

Community
  • 1
  • 1
Noctis
  • 11,507
  • 3
  • 43
  • 82