0

I have an AppearingCommand called when a Page appears in my Xamarin.Forms project, that eventually executes the following sqlite-net-pcl line: (I already have a mechanism coping with loading time)

AppearingCommand = new Command( async() => {
    //...
    var data = await db.Table<PlantCategory>().ToListAsync();
    //...
}

I want to move this method to the constructor, but I cannot do it, as it hangs if it is executed synchronously:

ctor() {
    //...
    var data = db.Table<PlantCategory>().ToListAsync().Result;
    //...
}

The line never returns (I am guessing because of a deadlock or something). What are other options that I have if I want to execute this line inside the constructor?

iSpain17
  • 1,739
  • 1
  • 10
  • 23
  • Possible duplicate of [Call asynchronous method in constructor?](https://stackoverflow.com/questions/23048285/call-asynchronous-method-in-constructor) – Pavel Anikhouski Jul 24 '19 at 12:12
  • It's not a duplicate, I already have a mechanism to cope with loading time. It is irrelevant for the question. I know it is possible, that's not my question – iSpain17 Jul 24 '19 at 12:16

1 Answers1

5

Simple. Don't.

Instead, add a post-construction method like async ValueTask InitAsync() and call that with await.

You could hide this behind a static ValueTask<Whatever> CreateAsync(...) method that you call instead of new Whatever(...), i.e.

class Whatever {
    private Whatever(...) { ... } // basic ctor
    private async ValueTask InitAsync(...) { ... } // async part of ctor

    public static async ValueTask<Whatever> CreateAsync(...) {
        var obj = new Whatever(...);
        await obj.InitAsync(...);
        return obj;
    }
}
Marc Gravell
  • 927,783
  • 236
  • 2,422
  • 2,784