【问题标题】:Close the form only after task has been completed仅在任务完成后关闭表单
【发布时间】:2018-12-25 09:43:14
【问题描述】:

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

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();
}

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

【问题讨论】:

    标签: c# async-await task


    【解决方案1】:

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

             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);
                    });
                }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2016-06-02
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      相关资源
      最近更新 更多