I changed from Client.DownloadFile to Client.DownloadFileAsync and i get exception:

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chocolade
    New Member
    • Aug 2010
    • 69

    I changed from Client.DownloadFile to Client.DownloadFileAsync and i get exception:

    I have a program that is downloading files every 3 seconds or the user time in seconds he choose. For the example of the problem its every 3 seconds.

    Now it was working good without problems untill i wanted to make the downloads async. Since i changed it to async im getting exception and i cant figure out what is the problem or/and how to solve it.

    So first thing in the constructor i added this line wich register me to the DownloadFileCom pleted event:

    Code:
    Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
    Then i have a timer1 wich is going down for example 3 2 1...and so on...
    Inside this timer1 event code im also calling a function i called it: filesdownload()

    Code:
    private void timer1_Tick(object sender, EventArgs e)
            {
                    try
                    {
                        numbers = Convert.ToInt64(textBox1.Text);
                        if (numbers <= 0)
                        {
                            timer1.Stop();
                            button1.Enabled = true;
                            textBox1.Enabled = true;
                            MessageBox.Show("Value cannot be zero or below zero");
                            textBox1.Text = "";
                        }
                        else
                        {
                            Numbers_Timer = Numbers_Timer + 1;
                            if (Numbers_Timer >= numbers)
                            {
                                try
                                {
                                    filesdownload();
                                    number_of_files_in_current_directory = Directory.GetFiles(sf, "radar*.jpg");
                                    label8.Text = "Current Number Of Files In The Selected Directory Are: " + number_of_files_in_current_directory.Length;
                                    button1.Enabled = false;
                                    Numbers_Timer = 0;
                                }
                                catch (Exception Local_Timer1_Exceptions)
                                {
                                    Logger.Write("Error :" + Local_Timer1_Exceptions);
                                }
                            }
                            time_left = numbers - Numbers_Timer;
                            label1.Text = "Time left for the next radar image to be download: " + time_left;
                        }
    
                    }
                    catch (Exception General_Exceptions)
                    {
                        timer1.Stop();
                        textBox1.Clear();
                        button1.Enabled = true;
                        textBox1.Enabled = true;
                        Numbers_Timer = 0;
                    }
                }
    Now after it i have the filesdownload() function wich in there im starting to download the file every 3 seconds async!

    Code:
    private void filesdownload()
            {
                string url;
                url = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=";
                if (!Directory.Exists(sf))
                {
                    timer1.Enabled = false;
                }
                    
                
                    Client.DownloadFileAsync(new Uri(url), temp_dir + temp_file);
             }
    Then in the end of my form1 code i have the Client_Download FileCompleted event wich in there im doing some tests and checks on the file that was download each time i mean every 3 seconds a file downloaded and the download is completed then its checking the file with some tests.

    Code:
    void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
             {
                 
                     string Next_File;
                     bool file_compare;
                     int i;
                     bool bad_file;
                     progressBar1.Maximum = 10;
                     progressBar1.Minimum = 0;
                     progressBar1.TabIndex = 0;
                     progressBar1.Value = 0;
                     progressBar1.Step = 10;
                     progressBar1.PerformStep();
                     button1.Enabled = true;
                     file_array_dl = Directory.GetFiles(sf, "radar*.jpg");
                     if (file_array_dl.Length == 0)
                     {
                         File.Copy(temp_dir + temp_file, sf + @"\radar001.jpg");
                     }
                     else
                     {
                         i = last_image_file();
                         last_file = sf + @"\radar" + i.ToString("D3") + ".jpg";
                         File.Copy(last_file, bad_file_test_dir + testing_file);
                         bad_file = Bad_File_Testing(bad_file_test_dir + testing_file);
                         if (bad_file == true)
                         {
                             File.Delete(bad_file_test_dir + testing_file);
                             if (File.Exists(last_file))
                             {
                                 file_compare = File_Utility.File_Comparison(temp_dir + temp_file, last_file);
                                 if (file_compare == true)
                                 {
                                     return;
                                 }
                                 i = last_image_file() + 1;
                                 Next_File = sf + @"\radar" + i.ToString("D3") + ".jpg";
                                 File.Copy(temp_dir + temp_file, Next_File);
                                 pictureBox1.Load(Next_File); 
                                     progressBar1.Maximum = 10;
                                     progressBar1.Minimum = 0;
                                     progressBar1.TabIndex = 0;
                                     progressBar1.Value = 0;
                                     progressBar1.Step = 10;
                                     progressBar1.PerformStep();
                                 button1.Enabled = true;
                             }
                         }
                         else
                         {
                             File.Delete(last_file);
                             File.Delete(bad_file_test_dir + testing_file);
                         }
    
                     }
    
                     Logger.Write("File Downloaded");
                 }

    Now when im connected to the internet the downloading is working fine no problems.
    When i disconnected from the internet manualy for testing then the program dosent stuck and its keeping downloading i mean its trying to download like once counting 3 2 1 then again 3 2 1 but in the second time the seconds dosent reset back to 3 but its keeping counting 0 -1 -2 -3 -4 -5....and so on untill i stop the program.

    Now i tried using breakpoints and couldnt find the problem or how to fix it.

    The error/exception im getting when im disconnected from the internet is:

    16/10/2010 13:09:29 -> Error :System.NotSupp ortedException: WebClient does not support concurrent I/O operations.
    at System.Net.WebC lient.ClearWebC lientState()
    at System.Net.WebC lient.DownloadF ileAsync(Uri address, String fileName, Object userToken)
    at WindowsFormsApp lication1.Form1 .filesdownload( ) in D:\C-Sharp\Download File\Downloadin g-File-Project-Version-008\Downloading File\Downloadin g File\Form1.cs:l ine 308
    at WindowsFormsApp lication1.Form1 .timer1_Tick(Ob ject sender, EventArgs e) in D:\C-Sharp\Download File\Downloadin g-File-Project-Version-008\Downloading File\Downloadin g File\Form1.cs:l ine 265

    Also another thing is when im disconnected from the internet and it keep downloading try to download im getting an error on:

    Program.cs
    Under the last line wich is Application.Run (new Form1()); on the closing symbol } im getting exception:

    Exception has been thrown by the target of an invocation

    System.Reflecti on.TargetInvoca tionException was unhandled
    Message=Excepti on has been thrown by the target of an invocation.
    Source=mscorlib
    StackTrace:
    at System.RuntimeM ethodHandle._In vokeMethodFast( Object target, Object[] arguments, SignatureStruct & sig, MethodAttribute s methodAttribute s, RuntimeTypeHand le typeOwner)
    at System.Reflecti on.RuntimeMetho dInfo.Invoke(Ob ject obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityC hecks)
    at System.Delegate .DynamicInvokeI mpl(Object[] args)
    at System.Windows. Forms.Control.I nvokeMarshaledC allbackDo(Threa dMethodEntry tme)
    at System.Windows. Forms.Control.I nvokeMarshaledC allbackHelper(O bject obj)
    at System.Threadin g.ExecutionCont ext.runTryCode( Object userData)
    at System.Runtime. CompilerService s.RuntimeHelper s.ExecuteCodeWi thGuaranteedCle anup(TryCode code, CleanupCode backoutCode, Object userData)
    at System.Threadin g.ExecutionCont ext.Run(Executi onContext executionContex t, ContextCallback callback, Object state)
    at System.Windows. Forms.Control.I nvokeMarshaledC allback(ThreadM ethodEntry tme)
    at System.Windows. Forms.Control.I nvokeMarshaledC allbacks()
    at System.Windows. Forms.Control.W ndProc(Message& m)
    at System.Windows. Forms.Control.C ontrolNativeWin dow.WndProc(Mes sage& m)
    at System.Windows. Forms.NativeWin dow.DebuggableC allback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    at System.Windows. Forms.UnsafeNat iveMethods.Disp atchMessageW(MS G& msg)
    at System.Windows. Forms.Applicati on.ComponentMan ager.System.Win dows.Forms.Unsa feNativeMethods .IMsoComponentM anager.FPushMes sageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
    at System.Windows. Forms.Applicati on.ThreadContex t.RunMessageLoo pInner(Int32 reason, ApplicationCont ext context)
    at System.Windows. Forms.Applicati on.ThreadContex t.RunMessageLoo p(Int32 reason, ApplicationCont ext context)
    at WindowsFormsApp lication1.Progr am.Main() in D:\C-Sharp\Download File\Downloadin g-File-Project-Version-008\Downloading File\Downloadin g File\Program.cs :line 19
    at System.AppDomai n._nExecuteAsse mbly(Assembly assembly, String[] args)
    at System.Runtime. Hosting.Applica tionActivator.C reateInstance(A ctivationContex t activationConte xt, String[] activationCusto mData)
    at Microsoft.Visua lStudio.Hosting Process.HostPro c.RunUsersAssem blyDebugInZone( )
    at System.Threadin g.ExecutionCont ext.Run(Executi onContext executionContex t, ContextCallback callback, Object state)
    at System.Threadin g.ThreadHelper. ThreadStart()
    InnerException: System.IO.IOExc eption
    Message=The file 'C:\Users\Choco lade\AppData\Lo cal\Microsoft\W indowsFormsAppl ication1\Bad_Fi le-Test\testing_fi le.jpg' already exists.
    Source=mscorlib
    StackTrace:
    at System.IO.__Err or.WinIOError(I nt32 errorCode, String maybeFullPath)
    at System.IO.File. InternalCopy(St ring sourceFileName, String destFileName, Boolean overwrite)
    at System.IO.File. Copy(String sourceFileName, String destFileName)
    at WindowsFormsApp lication1.Form1 .Client_Downloa dFileCompleted( Object sender, AsyncCompletedE ventArgs e) in D:\C-Sharp\Download File\Downloadin g-File-Project-Version-008\Downloading File\Downloadin g File\Form1.cs:l ine 1386
    InnerException:



    I dont know why the async dosent work and what did i do wrong.

    Thanks for helping.
Working...