【问题标题】:How to save program state on program close using aync file operations如何使用异步文件操作在程序关闭时保存程序状态
【发布时间】:2020-12-25 11:20:53
【问题描述】:

如果用户在程序仍在运行时关闭程序或启动关机,我正在尝试保存程序状态,但在这种情况下,不等待任务并且程序在写入设置期间终止导致文件损坏。如何在不创建额外的同步保存方法的情况下做到这一点?

private async void Window_Closed(object sender, EventArgs e)
{
    await programState.Save();
}

//from programState class
private async Task Save()
{        
    var state = JsonConvert.SerializeObject(progState, Formatting.Indented);
    using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
    {
        using (var sw = new StreamWriter(stream))
            await sw.WriteAsync(state).ConfigureAwait(true);
    } 
}

【问题讨论】:

标签: c# .net wpf async-await


【解决方案1】:

在这种情况下不需要使用 streams async 方法,只需在 同步 路径上使用常规 StreamWriter.Write(即不要使用异步和等待模式)。

但是,如果您真的需要使用类似 Window_Closed 的事件中的 async 和 await 模式,并且需要等待它(仍然知道在在这种情况下),您将必须删除 Window_Closed 事件上的 async void卸载工作;然后等待它(不推荐)

private void Window_Closed(object sender, EventArgs e)
{
    Task.Run(() => programState.Save()).Wait();
}

注意同步运行异步代码通常会导致中的死锁 >UI 框架,因为延续与 MessagePumpDispatchers 一起工作的方式。在这种情况下,您将async 工作卸载到线程池并通过牺牲线程 消除死锁。总之,不做,同步保存到流中就可以了

【讨论】:

  • 如果你仍然阻塞 UI 线程,为什么要Task.Run
  • @PauloMorgado 因为应用程序可能会提前关闭。但是是的,这里不需要异步或任务运行
猜你喜欢
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 2013-05-11
相关资源
最近更新 更多