How to continue executing code after calling ShowDialog()

后端 未结 7 833
走了就别回头了
走了就别回头了 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:32

    I suppose next solution for async ShowDialog:

    public bool DialogResultAsync
    {
        get;
        private set;
    }
    
    public async Task ShowDialogAsync()
    {
        var cts = new CancellationTokenSource();
        // Attach token cancellation on form closing.
        Closed += (object sender, EventArgs e) =>
        {
            cts.Cancel();
        };
        Show(); // Show message without GUI freezing.
        try
        {
            // await for user button click.
            await Task.Delay(Timeout.Infinite, cts.Token);
        }
        catch (TaskCanceledException)
        { } 
    }
    
    public void ButtonOkClick()
    {
        DialogResultAsync = true;
        Close();
    }
    
    public void ButtonCancelClick()
    {
        DialogResultAsync = false;
        Close();
    }
    

    And in main form you must use this code:

    public async void ShowDialogAsyncSample()
    {
        var msg = new Message();
        if (await msg.ShowDialogAsync())
        {
            // Now you can use DialogResultAsync as you need.
            System.Diagnostics.Debug.Write(msg.DialogResultAsync);
        }
    }
    

提交回复
热议问题