Click here to Skip to main content
15,443,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the code below works fine let's say i have a three files to download the first 2 is 2MB and the third is 12MB it downloads all the files correctly but after downloading the first 2 files it fires downloadfilecompleted event but after the third file it doesn't fire.
if i try to move this file or doing anything to it >> it's used by another process
and it never completes until i stop the debugging
after i stop debugging i look at the third file it's downloaded correctly
so i dunno why this event is not firing after downloading this file
i used breakpoints through all code and it seems that there's no exception is thrown
but the scenario here is the thread is frozen after downloading this third file.

Note: this file is not invalid file or corrupted file it's fine i downloaded it with browser,download tools,etc it's fine and the application also downloads it fine.

my code :
C#
#region private fields
        private bool isFinished = false;
        private List<DownloadFileInfo> downloadFileList = null;
        private List<DownloadFileInfo> allFileList = null;
        private ManualResetEvent evtDownload = null;
        private ManualResetEvent evtPerDonwload = null;
        private static WebClient clientDownload;
        long total = 0;
        long nDownloadedTotal = 0;
#endregion

#region The ConStructor of DownloadProgress
        public DownloadProgress(List<DownloadFileInfo> downloadFileListTemp)
        {
            PureEye.DailyOperation.FrmMain.UpdateStatus = 1;
            InitializeComponent();

            this.downloadFileList = downloadFileListTemp;
            allFileList = new List<DownloadFileInfo>();
            foreach (DownloadFileInfo file in downloadFileListTemp)
            {
                allFileList.Add(file);
            }
        }
        #endregion

private void OnFormLoad(object sender, EventArgs e)
        {
            evtDownload = new ManualResetEvent(true);
            evtDownload.Reset();
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcDownload));
        }

private void ProcDownload(object o)
        {
            string tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
            if (!Directory.Exists(tempFolderPath))
            {
                Directory.CreateDirectory(tempFolderPath);
            }


            evtPerDonwload = new ManualResetEvent(false);
            long totalfilesize = 0;
            foreach (DownloadFileInfo file in this.downloadFileList)
            {
                total += file.Size;
            }
            try
            {
                while (!evtDownload.WaitOne(0, false))
                {
                    if (this.downloadFileList.Count == 0)
                        break;

                    DownloadFileInfo file = this.downloadFileList[0];
                    totalfilesize = file.Size;
                    //progressBarCurrent.Maximum = totalfilesize;

                    //Debug.WriteLine(String.Format("Start Download:{0}", file.FileName));

                    this.ShowCurrentDownloadFileName(file.FileName);

                    //Download
                    clientDownload = new WebClient();
                    NetworkCredential objCred = new NetworkCredential();
                    objCred.UserName = ftpUserID;
                    objCred.Password = ftpPassword;
                    //Added the function to support proxy

                    clientDownload.Proxy.Credentials = objCred;
                    clientDownload.Credentials = objCred;
                    //End added

                    clientDownload.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
                    {
                        try
                        {
                            int filePercentage = (int)(e.BytesReceived * 100 / totalfilesize);
                            int totalPercentage = (int)((nDownloadedTotal + e.BytesReceived) * 100 / total);

                            this.SetProcessBar(filePercentage, totalPercentage);
                        }
                        catch
                        {
                            //log the error message,you can use the application's log code
                        }

                    };
                    clientDownload.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                    {
                        try
                        {
                            DealWithDownloadErrors();
                            DownloadFileInfo dfile = e.UserState as DownloadFileInfo;
                            nDownloadedTotal += dfile.Size;
                            this.SetProcessBar(0, (int)(nDownloadedTotal * 100 / total));
                            evtPerDonwload.Set();
                        }
                        catch (Exception)
                        {
                            //log the error message,you can use the application's log code
                        }

                    };

                    evtPerDonwload.Reset();

                    //Download the folder file
                    string tempFolderPath1 = CommonUnitity.GetFolderUrl(file);
                    if (!string.IsNullOrEmpty(tempFolderPath1))
                    {
                        tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
                        tempFolderPath += tempFolderPath1;
                    }
                    else
                    {
                        tempFolderPath = Path.Combine(CommonUnitity.SystemBinUrl, ConstFile.TEMPFOLDERNAME);
                    }

                    clientDownload.DownloadFileAsync(new Uri(file.DownloadUrl), Path.Combine(tempFolderPath, file.FileFullName), file);
                    //Wait for the download complete
                    evtPerDonwload.WaitOne();
                    clientDownload.Dispose();
                    clientDownload = null;

                    //Remove the downloaded files
                    this.downloadFileList.Remove(file);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                ShowErrorAndRestartApplication();
                //throw;
            }

            //When the files have not downloaded,return.
            if (downloadFileList.Count > 0)
            {
                return;
            }

            //Test network and deal with errors if there have 
            DealWithDownloadErrors();

            //Debug.WriteLine("All Downloaded");
            foreach (DownloadFileInfo file in this.allFileList)
            {
                string tempUrlPath = CommonUnitity.GetFolderUrl(file);
                string oldPath = string.Empty;
                string newPath = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(tempUrlPath))
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1), file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + ConstFile.TEMPFOLDERNAME + tempUrlPath, file.FileName);
                    }
                    else
                    {
                        oldPath = Path.Combine(CommonUnitity.SystemBinUrl, file.FileName);
                        newPath = Path.Combine(CommonUnitity.SystemBinUrl + ConstFile.TEMPFOLDERNAME, file.FileName);
                    }

                    //just deal with the problem which the files EndsWith xml can not download
                    System.IO.FileInfo f = new FileInfo(newPath);
                    if (!file.Size.ToString().Equals(f.Length.ToString()) && !file.FileName.ToString().EndsWith(".xml"))
                    {
                        ShowErrorAndRestartApplication();
                    }


                    //Added for dealing with the config file download errors
                    string newfilepath = string.Empty;
                    if (newPath.Substring(newPath.LastIndexOf(".") + 1).Equals(ConstFile.CONFIGFILEKEY))
                    {
                        if (System.IO.File.Exists(newPath))
                        {
                            if (newPath.EndsWith("_"))
                            {
                                newfilepath = newPath;
                                newPath = newPath.Substring(0, newPath.Length - 1);
                                oldPath = oldPath.Substring(0, oldPath.Length - 1);
                            }
                            File.Move(newfilepath, newPath);
                        }
                    }
                    //End added

                    if (File.Exists(oldPath))
                    {
                        MoveFolderToOld(oldPath, newPath);
                    }
                    else
                    {
                        //Edit for config_ file
                        if (!string.IsNullOrEmpty(tempUrlPath))
                        {
                            if (!Directory.Exists(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1)))
                            {
                                Directory.CreateDirectory(CommonUnitity.SystemBinUrl + tempUrlPath.Substring(1));


                                MoveFolderToOld(oldPath, newPath);
                            }
                            else
                            {
                                MoveFolderToOld(oldPath, newPath);
                            }
                        }
                        else
                        {
                            MoveFolderToOld(oldPath, newPath);
                        }

                    }
                }
                catch (Exception exp)
                {
                    //log the error message,you can use the application's log code
                }

            }

            //After dealed with all files, clear the data
            this.allFileList.Clear();

            if (this.downloadFileList.Count == 0)
                Exit(true);
            else
                Exit(false);

            evtDownload.Set();
        }
Posted
Updated 20-Jun-12 1:17am
v4
Comments
Sergey Alexandrovich Kryukov 19-Jun-12 18:11pm     CRLF
Not clear. What is "not firing"? ManualResetEvent (which is EventWaitHandle)? This is not that kind of event which fires. Are you sure you are not mixing up .NET events with EventWaitHandle -- they are unrelated? --SA
Sergey Alexandrovich Kryukov 19-Jun-12 18:15pm     CRLF
Oh, I see, you probably mean DownloadFileCompleted... What are you trying to achieve. I would recommend using HttpWebRequest instead -- much more control, and much simpler. You see, if you use threads anyway, it renders asynchronous API making no sense... --SA
snake1 20-Jun-12 6:43am    
thanks for your reply , i switched to ftpwebrequest and it also works fine on the first 2 files but on the third file it caught an exception "The underlying connection was closed: An unexpected error occurred on a receive." i tried to download this file with download tools again it cannot be downloaded without resuming the download it disconnects on 96% - 99% i dunno why
snake1 20-Jun-12 6:48am    
the file is not corrupted but i don't know if the server disconnects due to delay , the first 2 files are 2MB and the third is 13MB it's not that big
snake1 20-Jun-12 6:52am    
i think this issue is not because of using webclient,threads it's happening even if i use ftpwebrequest and also it happens while using download tools

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900