仅在任务完成后关闭表单

时间:2018-12-25 09:43:15

标签: c# async-await task

我有一个清理任务,该任务会在退出时删除一个大文件。

private async Task DoCleanup()
{
    await Task.Run(() =>
    {
        File.Delete(FilePath);
    });
}

现在,我想在退出(FormClosing事件)时等待该任务,但是在文件被完全删除之前,该窗体将关闭。

我试图取消该事件并手动退出该应用程序,如下所示:

private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   this.Hide();
   e.Cancel = true;
   await DoCleanup();
   Application.Exit();
}

但是一遍又一遍地调用Task(就像一个无限循环)。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以创建一个调用函数的事件,并在Application.Close()完成时将该事件绑定到Task

         public async static Task Main(string[] args)
            {

YourClassName classInstance = new YourClassName();

                // Bind the event to something
                classInstance .CompletedTaskEvent += (s, e) => Console.WriteLine("Completed work");

                // Start the work
                await classInstance.DoCleanup();

                Console.ReadLine();
            }


    public class YourClassName
    {
            // Some event
            public event EventHandler CompletedTaskEvent;


            public async Task DoCleanup()
            {
                await Task.Run(async () =>
                {
                    await Task.Delay(2500);

                    // When the task completes invoke the event
                    // And pass the current class instance to the sender
                    // And you can add any kind of event argument you want
                    // however I recommend you make the event generic and then pass the argument type
                    CompletedTaskEvent?.Invoke(this, eventArguments);
                });
            }
    }