C# OpenReadTaskAsync工作不正常?
所以我试着让后台代理每30秒下载一张图片。调用该函数时,它将调用此函数“DownloadImageFromServer”。使用断点,我发现它命中了OpenReadTaskAsync函数调用,但似乎跳过了剩余的代码(那里的断点从未命中)。此外,它还没有下载图像。你知道是什么引起的吗C# OpenReadTaskAsync工作不正常?,c#,visual-studio-2012,windows-phone-8,C#,Visual Studio 2012,Windows Phone 8,所以我试着让后台代理每30秒下载一张图片。调用该函数时,它将调用此函数“DownloadImageFromServer”。使用断点,我发现它命中了OpenReadTaskAsync函数调用,但似乎跳过了剩余的代码(那里的断点从未命中)。此外,它还没有下载图像。你知道是什么引起的吗 private async void DownloadImagefromServer(string imgUrl) { Debug.WriteLine("Attempting to
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);
}
如果您使用的是.NET 4.5,则只需创建一个新的
webclient
,并使用async下载该文件即可
例如:
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");
}
不要使用
async void
。我应该使用什么呢?async Task
是您应该使用的async void
仅用于“触发并忘记”异步方法,如事件处理程序。您不能使用await
异步void方法。当我将其更改为async task
并让其返回任务时,VS会给我错误错误“await”运算符只能在异步方法中使用。考虑将此方法标记为“AsiNC”修饰符并将其返回类型改为“任务”< /代码>。这与我的OpenReadTaskAsync
方法位于同一行