首页 > 解决方案 > 当 EC2 实例关闭时,如何优雅地关闭我的应用程序?

问题描述

我有一个需要运行数小时的数据处理应用程序。我们的一位客户在定义了关闭计划的 AWS EC2 Windows 2012 实例上运行它。结果,它在每次运行过程中不断被切断。

这不会对数据处理本身造成问题:每个数据行都是原子处理的,之后可以安全地重新启动它,而无需重新执行任何已处理的数据行。但是,它确实在过程结束时将大量摘要数据写入磁盘,我真的可以通过查看来完成,并且这些数据没有被写入。

该应用程序是用 VB.NET WinForms 编写的。有一个在屏幕上显示进度的表单,处理逻辑是通过BackgroundWorker组件完成的。

表单按如下方式处理取消事件:

Private Sub MyBase_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing

    ' If the user tried to close the app, ask if they are sure, and if not, then don't close down.
    If e.CloseReason = CloseReason.UserClosing AndAlso ContainsFocus AndAlso Not PromptToClose() Then
        e.Cancel = True
        Return
    End If

    ' If the background worker is running, then politely request it to stop. Otherwise, let the form close down.
    If worker.IsBusy Then
        If Not worker.CancellationPending Then
            worker.CancelAsync()
        End If
        e.Cancel = True
    Else
        Environment.ExitCode = AppExitCode.Cancelled
    End If

End Sub

每处理一个数据行,后台线程都会轮询一次取消,如下所示:

Private Sub ReportProgress(state as UIState)
    worker.ReportProgress(0, state)
    If worker.CancellationPending Then
        Throw New AbortException ' custom exception type
    End If
End Sub

后台线程中的顶级Catch块适当地处理所有成功和失败路径,在退出线程之前将所有摘要数据写入磁盘。

我已经在 AWS 之外对此进行了广泛的测试。特别是,我已经验证,如果您通过任务管理器结束进程,那么它会在不提示用户的情况下立即优雅地关闭,并将所有摘要数据按预期写入磁盘。正常关机最多需要几秒钟。

我的问题是,当 AWS 按计划关闭 EC2 实例时,摘要数据没有写入磁盘。我不确切知道在 EC2 关闭过程中会发生什么,而且我对 EC2 文档的搜索还没有阐明这一点。我想它可能是以下之一:

谁能澄清 EC2 关闭过程的工作原理,或者建议我如何改进我的代码来处理它?

标签: windowsamazon-web-serviceswinformsamazon-ec2

解决方案


推荐阅读