C# 在windows 8中删除存储文件

C# 在windows 8中删除存储文件,c#,windows-8,windows-runtime,C#,Windows 8,Windows Runtime,我想每10秒拍一次照片。为此,我将使用Timer类,该类将运行以下代码: async private void captureImage() { capturePreview.Source = captureManager; await captureManager.StartPreviewAsync(); ImageEncodingProperties imgFormat = ImageEncodingProperties.Creat

我想每10秒拍一次照片。为此,我将使用Timer类,该类将运行以下代码:

 async private void captureImage()
    {
        capturePreview.Source = captureManager;
        await captureManager.StartPreviewAsync();

        ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();


        // create storage file in local app storage
        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
            "TestPhoto.jpg",
            CreationCollisionOption.GenerateUniqueName);


        // take photo
        await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);

        // Get photo as a BitmapImage
        BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));

        // imagePreivew is a <Image> object defined in XAML
        imagePreivew.Source = bmpImage;


        await captureManager.StopPreviewAsync();    
        //send file to server
        sendHttpReq();

         await file.DeleteAsync(StorageDeleteOption.PermanentDelete); 


    }
async private void captureImage()
{
capturePreview.Source=captureManager;
等待captureManager.StartPreviewSync();
ImageEncodingProperties imgFormat=ImageEncodingProperties.CreateJpeg();
//在本地应用程序存储中创建存储文件
StorageFile文件=等待ApplicationData.Current.LocalFolder.CreateFileAsync(
“TestPhoto.jpg”,
CreationCollisionOption.GenerateUniqueName);
//拍照
等待captureManager.CapturePhotoToStorageFileAsync(imgFormat,file);
//将照片获取为位图图像
BitmapImage bmpImage=新的BitmapImage(新的Uri(file.Path));
//imagePreivew是在XAML中定义的对象
imagePreivew.Source=bmp图像;
等待captureManager.stopReviewSync();
//将文件发送到服务器
sendHttpReq();
wait file.deleteAncy(StorageDeleteOption.PermanentDelete);
}
目前我在点击按钮时调用上述函数


我想删除图像传输后的文件,因为我将把它发送到web服务器。然而,我看不到imagePreivew在点击按钮时得到更新,而当我不删除文件时,我每次按下按钮时都会看到imagePreivew更改。我也尝试过CreationCollisionOption.replace,但仍然面临同样的问题。每次计时器执行任务时创建新文件都会浪费大量内存。如何删除文件

问题在于,您正在删除加载前的图像(位图是异步加载的)

要解决这个问题,只需替换

//将照片作为位图图像获取
BitmapImage bmpImage=新的BitmapImage(新的Uri(file.Path));

使用(irandomaccesstream fileStream=await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bmpImage=新的BitmapImage();
等待bmpImage.SetSourceAsync(文件流);
}
这样,在删除之前,您将等待图像加载完成

您还应该等待
sendHttpReq()
,否则在将请求发送到服务器之前,图像也将被删除


另一件您可能需要纠正的事情是,在上一次捕获未完成时,可能会再次调用captureImage。要解决此问题,您可以使用ISSTILLCATPING标志并在其仍在捕获时返回,或者使用来防止两个CapturePhotoToStorageFileAsync同时发生。

一个建议:将sendHttpReq和DeleteAsync等辅助操作放入另一个异步函数中,您可以在captureImage中调用该函数,但不能等待。这样,您就可以从captureImage返回,并让其他内容并行运行。@KraigBrockschmidt MSFT实际上captureImage甚至没有返回任务,所以它是同步执行的,所以它会在第一次等待完成后立即“返回”,所以这并不重要。