How to continue executing code after calling ShowDialog()

后端 未结 7 832
走了就别回头了
走了就别回头了 2020-12-17 10:58

the Form.ShowDialog() method causes the code to be halted until the newly called form is closed. I need the code to continue running after the ShowDialog() method is called.

7条回答
  •  清酒与你
    2020-12-17 11:17

    As long as you do asynchronous operations during the time that the modal dialog is opened, you can do it as simply as shown below, assuming button1_Click() is the event handler for a button.

    private async void button1_Click(object sender, EventArgs e)
    {
        // create and display modal form
        Form2 modalForm = new Form2();
        BeginInvoke((Action)(() => modalForm.ShowDialog()));
    
        // do your async background operation
        await DoSomethingAsync();
    
        // close the modal form
        modalForm.Close();
    }
    
    
    private async Task DoSomethingAsync()
    {
        // example of some async operation....could be anything
        await Task.Delay(10000);
    }
    

    I found that when I used the solution that suggested to use Show(), I could end up in cases where the dialog I wanted to be modal would end up behind the main form, after switching back and forth between apps. That never happens when I use the solution above.

提交回复
热议问题