0

I have the following prolblem from an existing code base: The AsyncAwaitQuestion1 calls an async method inside a Task.Run, from the caller(my code), I need to wait for the underlying private async method to be completed. How is a clean/not-so-dirty way to accomplish this?

see below

public class AsyncAwaitQuestion1
{
    public List<string> MyList;

    public AsyncAwaitQuestion1()
    {
        MyList = new List<string>() { "a", "b" };
        Task.Run(() => DoSomethingAsync());
    }

    private async Task DoSomethingAsync()
    {
        await Task.Delay(new TimeSpan(0, 0, 0, 0, 10));
        await Task.Delay(new TimeSpan(0, 0, 0, 2));
        await Task.Delay(new TimeSpan(0, 0, 0, 3));
        MyList.Add("c");
        await Task.Delay(new TimeSpan(0, 0, 0, 4));
        MyList.Add("d");
    }

}

    private void Button_Click_3(object sender, RoutedEventArgs e)
    {
        var question = new AsyncAwaitQuestion1();
        int x = 0;//I would like to read all the 4 elements here
    }
AmandaSai98b
  • 485
  • 1
  • 7
  • 17
  • 4
    The constructor is *usually* the wrong place to have this sort of behaviour, OOP objects are about encapsulation, you construct them to use them. Waiting on an object to construct asynchronously (with no innate framework support), its not optimal and can lead to maintainability problems, weird stack traces, and non intuitive / non idiomatic code. Can you perhaps explain the use case here, or what problem you are trying to solve with this design? – TheGeneral Dec 08 '21 at 00:45
  • 1
    If you are going to want to fire something off async in the constructor, then you probably want to hold the task that is returned as a private field in the class. That way, if someone wants to do something with the object later, you can see if the task is finished (to make a decision what to do), await that task, whatever. But I agree with @TheGeneral: awaiting something async in a constructor is likely a bad idea (unless you have a *really* good reason – Flydog57 Dec 08 '21 at 00:52
  • 1
    You could just make the constructor private and add an public static async 'createblah' method that acts as a constructor. Within the static method you are allowed to await stuff. This a static factory method design pattern. – jmik Dec 08 '21 at 01:27

0 Answers0