Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

c# - WebClient AsyncUpload progress percentage always returns 50%

i am using Webclient to upload data using Async call to a server,

    WebClient webClient = new WebClient();
   webClient.UploadDataAsync(uri , "PUT", buffer, userToken);

i've attached DatauploadProgress and DatauploadCompleted Events to appropriate callback functions

        // Upload Date Progress
        webClient.UploadProgressChanged += new 
        UploadProgressChangedEventHandler(UploadProgressCallback);

      // Upload Date Progress
     void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
    {
        // Magic goes here 
     logger.writeToLog("Percentage =" + e.ProgressPercentage);
    }

the e.ProgressPercentage always returns 50 .. no matter what the size of the file uploaded was (tried different sizes between 10kb to 60mb ). the function itself gets called only twice (really fast too) and percentage shows 50! ..which is illogical specially with big files ...

e.BytesSent doesn't help either..it always shows the files size in bytes :S (ex: if the file size was 63,000 , i'd get e.BytesSent = 63,000and e.ProgressPercentage= 50

Can someone point the problem out to me ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to monitor the progress of an upload, you'll need to use UploadFileAsync instead of UploadData.

With UploadDataAsync you are supposed to manually chunk the file and display the progress (at least, that's what I've determined from my own experience in the matter though I haven't seen it written as such on MSDN).

What you're looking for is to use UploadFileAsync instead, which will call the UploadProgressChanged event correctly. You can then view the event args properties BytesSent and TotalBytesToSend which should be reflected correctly.

I assume the rationale behind this is that when you're sending data, you can loop over chunks of your data stream and manually increment your progress tracker whereas with a file you cannot (.NET will manage the entire upload for you). Personally, I feel there is something fishy because there is no reason for the UploadProgressChanged event to be called with invalid information in case of UploadDataAsync - either it is called with valid, correct info or it's not called at all.

At any rate, give UploadFileAsync a shot and see how that goes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...