My application used BackgroundWorker to upload a file to an FTP server. Everything works fine, but it seems that the OnProgressChanged event OnProgressChanged not working as it should.
I, although OnProgressChanged will finish completely after the RunWorkerCompleted event, but it is not.
In my case, the OnProgressChanged event still fires, although RunWorkerComplete fired. Obviously, my progress indicator is still ongoing, as long as my file is already fully uploaded to the ftp server.
I tested in my debug mode and I see that after RunWorkerCompleted Fired, OnPorgressChanged still works.
My code is here.
void FTP_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bw = sender as BackgroundWorker; try { string filename = e.Argument.ToString(); if (filename != string.Empty) { FileInfo fileInf = new FileInfo(filename); FtpWebRequest reqFTP; if (!IsFolderExist(_defaultDir)) { MakeDefaultDir(_defaultDir); } reqFTP = GetRequest(this._host, this._port, GetDirName(_defaultDir) + "/" + fileInf.Name, this._user, this._pass); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; long FileSize = fileInf.Length; string FileSizeDescription = GetFileSize(FileSize); int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50; long SentBytes = 0; byte[] Buffer = new byte[ChunkSize]; int BytesRead = 0; using (Stream requestStream = reqFTP.GetRequestStream()) { using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the first chunk in the buffer while (BytesRead > 0) { try { if (bw.CancellationPending) return; requestStream.Write(Buffer, 0, BytesRead); SentBytes += BytesRead; // Here is progress information string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription); bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.ToString()); if (NumRetries++ < MaxRetries) { fs.Position -= BytesRead; } else { throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString())); } } BytesRead = fs.Read(Buffer, 0, ChunkSize); } } } } } catch (Exception ex) { if (OnFTPError != null) { OnFTPError(this, "Error was handled in Replaced File Uploading :" + ex.Message); } } }
Any ideas on these issues? Thanks guys