1

I want to show an indefinite progress bar in a little WPF window of class BackgroundOperationWindow that I wrote. This is a simple window with an indefinite progress bar, but no "Cancel" button, since there is nothing to be cancelled.

It contains this method:

public async Task PerformAction( Action action )
{
    await Task.Run( () => action() );
}

and is used to show that connection to a server is in progress:

async void ConnectToServer( object sender, RoutedEventArgs e )
{
    var bo = new BackgroundOperationWindow();
    bo.Show();
    await bo.PerformAction( () =>
    {
        // This takes some time...
        Server.Connect(...)
    } );
}

My problem is: "ConnectToServer" shall not return until the connection is established. (Since the calling window of ConnectToServer is not yet visible at this time, it is no problem that it will be blocked). All the examples that I found using async/await use some kind of "Button_Click" scenario, where it's OK (and intended) that Button_Click returns before the task is completed.

In other words: I want to get rid of the "async" in async void ConnectToServer(...). ConnectToServer shall not act asynchronously from its caller's perspective.

What I'm looking for is some kind of "Task.WaitAndKeepTheUIThreadRunningSoThatTheProgressBarAnimates()"

Heinz Kessler
  • 1,610
  • 11
  • 24
  • It's not quite user-friendly to show a blocking modal window just to wait for an end of an async operation. If however refactoring isn't an option, I believe I have a solution to your problem: https://stackoverflow.com/a/53510363/1768303 – noseratio Mar 04 '19 at 22:27

1 Answers1

0

Put the call to PerformAction in a Task of its own:

Task.Run(async () => await bo.Performan
    ...etc.
Mark Feldman
  • 15,731
  • 3
  • 31
  • 58
  • This doesn't solve the OP problem (he seems to want to run an async operation synchronously) but may potentially introduce a bunch of other issues related to [fire-and-forger](https://stackoverflow.com/q/22369179/1768303). – noseratio Mar 04 '19 at 22:32