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

Time:10-06

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();
                                                          }));
}

CodePudding user response:

public async void Init()
{
    var task = _device.Init();

    //do work here

    await task;

    Start();
}

Should do the trick, it'll do the work and then wait for the task to complete before going to Start();

If you want to simply wait for init to finish and then run start it's even simpler with

await _device.Init().ContinueWith((x) => { Start();})

CodePudding user response:

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();
  • Related