Awaiting Asynchronous function inside FormClosing Event

后端 未结 6 1152
星月不相逢
星月不相逢 2020-11-27 20:59

I\'m having a problem where I cannot await an asynchronous function inside of the FormClosing event which will determine whether the form close should continue. I have crea

6条回答
  •  没有蜡笔的小新
    2020-11-27 21:19

    You can't keep your form from closing with async/await. And you can get strange results.

    What I would do is creating a Thread and setting its IsBackground property to false (which is false by default) to keep the process alive while form is closing.

    protected override void OnClosing(CancelEventArgs e)
    {
        e.Cancel = false;
        new Thread(() => { 
            Thread.Sleep(5000); //replace this line to save some data.....
            MessageBox.Show("EXITED"); 
        }).Start();
        base.OnClosing(e);
    }
    

提交回复
热议问题