OpenReadTaskAsync无法正常工作?

时间:2013-12-08 16:22:43

标签: c# visual-studio-2012 windows-phone-8

所以我试图让后台代理每30秒下载一次图像。调用它时,它调用此函数`DownloadImageFromServer'。使用断点,我发现它击中了OpenReadTaskAsync函数调用,但似乎跳过了剩余的代码(从未命中过的断点)。随着它不下载图像的事实。关于是什么导致这个问题的任何想法?

      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);


    }

1 个答案:

答案 0 :(得分:3)

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");
}