Search code examples
c#visual-studio-2012windows-phone-8

OpenReadTaskAsync not working properly?


So I am trying to have a background agent download an image every 30 seconds. When it is invoked, it calls this function `DownloadImageFromServer'. Using breakpoints, I have found that it hits the OpenReadTaskAsync function call, but then seems to skip over the remaining code (breakpoints there are never hit). Along with the fact that it does not download the image. Any ideas as to what is causing this?

      private async void DownloadImagefromServer(string imgUrl)
    {
        Debug.WriteLine("Attempting to Get Image from Server...");
        WebClient client = new WebClient();



    var result = await client.OpenReadTaskAsync(new Uri(imgUrl, UriKind.Absolute));
    //============================================================
    //THE BELOW CODE IS NEVER HIT WHEN PUT WITH BREAKPOINTS
    /=============================================================
            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(result);

            // Create a filename for JPEG file in isolated storage.
            String tempJPEG = "DownloadedWalleper.jpg";

            // Create virtual store and file stream. Check for duplicate tempJPEG files.
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(tempJPEG))
                {
                    myIsolatedStorage.DeleteFile(tempJPEG);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);

                StreamResourceInfo sri = null;
                Uri uri = new Uri(tempJPEG, UriKind.Relative);
                sri = Application.GetResourceStream(uri);


                WriteableBitmap wb = new WriteableBitmap(bitmap);

                // Encode WriteableBitmap object to a JPEG stream.
                Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);


                fileStream.Close();
            }
            LockScreenChange("DownloadedWalleper.jpg", false);


    }

Solution

  • If you are using .NET 4.5, you can just make a new webclient and download the file with async

    Example:

    private void btnDownload_Click(object sender, EventArgs e)
    {
      WebClient webClient = new WebClient();
      webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
      webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
      webClient.DownloadFileAsync(new Uri("http://example.com/myfile.txt"), @"c:\myfile.txt");
    }