79616946

Date: 2025-05-11 21:50:25
Score: 2
Natty:
Report link

I faced the same issue and spent several hours till the solution was found.

My scenario:

  1. I'm calling a dialog window with progress bar on board that downloads some files from web if they were not downloaded before.

  2. I want the download process to start automatically as soon as the dialog is opened

  3. I also want this dialog window to automatically close itself as soon as everything is downloaded.

Here is an example of my code:

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        StartCommand.Execute();
    }

    protected override async Task StartProgressAsync(CancellationToken cancellationToken)
    {
        // 1. do some time consuming download work
        await _filesDownloadService.DownloadSomeFilesAsync(cancellationToken);

        // 2. execute cancel command that closes the window.
        CloseCommand.Execute();
    }

    private void Close()
    {
        RaiseRequestClose(new DialogResult(ButtonResult.OK));
    }

    private void RaiseRequestClose(IDialogResult dialogResult)
    {
        var handler = RequestClose;
        handler?.Invoke(dialogResult);
    }

So, why sometimes the window is not closing itself?

It may happen if the download progress is executing faster than the logic that performing the dialog opening event, where the subscribtion to RequestClose event is performed.

How to fix it?

Ensure that RequestClose is not null before calling the CloseCommand

    protected override async Task StartProgressAsync(CancellationToken cancellationToken)
    {
        // 1. do some time consuming download work
        await _filesDownloadService.DownloadSomeFilesAsync();

        // 2. ensure RequestClose is not null.
        await WaitForRequestCloseAsync(repeatTimeout: 100);

        // 3. execute cancel command that closes the window.
        CloseCommand.Execute();
    }

    protected async Task WaitForRequestCloseAsync(int repeatTimeout)
    {
        while (true)
        {
            var handler = RequestClose;
            if (handler == null) await Task.Delay(repeatTimeout);
            else return;
        }
    }
Reasons:
  • RegEx Blacklisted phrase (1.5): How to fix it?
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Alex Valchuk