Search code examples
c#.netwpfasync-awaittask

Wait for a specific result from Task then run another method in C#


I have a WPF app running on .net 6 and an external device connected to it.

Initializing the device sometimes fails and I don't want to hold the UI thread trying to initialize it.

I want to run the following method (_device.Init()) in an async fashion and when it returns true, run Start() method.

edit: run it until it returns true from the _device.Init() method, not true for finishing the task

Is there a built-in functionality to do it with tasks? or any other "best practice" way?

Thank you :)

SomeDevice _device = new();

public async void Init()
{
    // some other code

    while (Task.Run(() => _device.Init()).Result == false)
    {

    }

    Start();
}


public void Start()
{
    // some other code

    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                                          {
                                                              _device.Start();
                                                          }));
}

Solution

  • Instead of getting the Result of the Task (which may block the UI thread) you should await the Task:

    public async void Init()
    {
        // some other code
    
        while (!await Task.Run(() => _device.Init()))
        {
        }
    
        Start();
    }
    

    The method should also be awaitable and be awaited when called, e.g. in an async Loaded event handler:

    public async Task Init()
    {
        // some other code
    
        while (!await Task.Run(() => _device.Init()))
        {
        }
    
        Start();
    }
    
    ...
    await Init();