我目前正在创建一个 Windows 商店应用程序 (C#),它定期(每 3 秒)从 URL 中提取图像并将其显示在页面上。图像已成功下载到临时应用程序存储一次,但第二次出现访问被拒绝 (UnauthorizedAccessException)。
这很可能是因为我的应用程序在尝试用新图像覆盖它时将该文件用作位图的源(因此它仍然处于打开状态)。
是否有避免并发问题的解决方法?
public async void GetLocalImageAsync(string internetUri, string uniqueName)
{
//Set up the web request and pass credentials.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(internetUri);
request.Credentials = new NetworkCredential("james", "jam3s");
//get response
using (var response = await request.GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
var desiredName = string.Format(uniqueName);
//create the file.
var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting);
using (var filestream = await file.OpenStreamForWriteAsync())
{
await stream.CopyToAsync(filestream);
//update the bitmap image with the file we just downloaded.
BitmapImage c1src = new BitmapImage(new Uri("ms-appdata:///temp/camera1imgsrc.png"));
camera1img.Source = c1src;
}
}
}
}