异步文件保存未正确执行C#

时间:2018-02-14 15:47:21

标签: c# file async-await save

我已经读过异步并等待,并认为这将是异步执行文件保存的正确方法,但它似乎仍然没有给我解决方案我'我正在寻找。

我有一个程序,在提示时会将照片还原为原始的未经编辑的表单。这涉及数据库中的更新,然后从目录中删除文件并将新文件写入目录然后显示。出现的问题(据我所知)是它会在文件完全写入之前更新然后显示。这并不是每次都会发生,但会在60%的时间内显示旧照片,刷新后会显示正确的照片。以下是恢复操作发生时的当前(相关)代码。

 void RevertPhoto(object sender, EventArgs e)
 {
      //Update Database here

      HandleFileAsync();
 }
 async void HandleFileAsync()
    {
        Task<int> task = ResaveFile();
        int count = await task;
        if(count == 1)
        {
            Thread.Sleep(1000); //I put this in here to see if it'd fix the issue, but I feel like this shouldn't be necessary.
            PicturePlaceholder.Controls.Clear(); //Clear the pictures on the next page
            GetPhotoInfo(Convert.ToInt32(hiddenICTASKID.Value)); //Reload pictures on next page

            showPanels(PanelPhotoReview); //Show the panel while hiding the rest.
            hidePanels(PanelCleanList, PanelSiteList, PanelImageSwap, Panel5, PanelRevertPhoto, PanelImageDelete);
        }
    }

    async Task<int> ResaveFile()
    {
        await Task.Run(() =>
        {
            if (File.Exists(RevertFolderPath.Value)) //These two lines shouldn't be necessary as WriteAllBytes will overwrite.
                File.Delete(RevertFolderPath.Value);

            string filePath = RevertFolderPath.Value;
            File.WriteAllBytes(filePath, Convert.FromBase64String(Base64RevertImage.Value));
        });
        return 1;
    }

这是接近它的正确方法还是我有点关闭?

1 个答案:

答案 0 :(得分:0)

将您的代码重构为

async void RevertPhoto(object sender, EventArgs e)
 {
      //Update Database here

      await HandleFileAsync();
 }
 async Task HandleFileAsync()
    {
        await ResaveFile();


            PicturePlaceholder.Controls.Clear(); //Clear the pictures on the next page
            GetPhotoInfo(Convert.ToInt32(hiddenICTASKID.Value)); //Reload pictures on next page

            showPanels(PanelPhotoReview); //Show the panel while hiding the rest.
            hidePanels(PanelCleanList, PanelSiteList, PanelImageSwap, Panel5, PanelRevertPhoto, PanelImageDelete);

    }
     async Task ResaveFile()
        {
            await Task.Factory.StartNew(() =>
            {
                if (File.Exists(RevertFolderPath.Value)) //These two lines shouldn't be necessary as WriteAllBytes will overwrite.
                    File.Delete(RevertFolderPath.Value);

                string filePath = RevertFolderPath.Value;
                File.WriteAllBytes(filePath, Convert.FromBase64String(Base64RevertImage.Value));
            });
        }