Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call async method from constructor?

I need to call a async method from my Form1 constructor. Since a constructor can't have a return type, I can't add a async void. I read that static constructor can be async but I need to call methods from constructor that aren't static, such as InitializeComponent() (since it's the Form's constructor).

The class is:

public partial class Form1 : Form
{
    InitializeComponent();
    //some stuff
    await myMethod();
}

I read this one too but I still don't know how to implement this (in my case) since the method still requires to use async.

like image 796
Jack Avatar asked Mar 14 '15 21:03

Jack


People also ask

Can a constructor call async function?

A simple answer for that: No, we can't! Currently, class constructors do not return types, and an asynchronous method should return a Task type. Don't worry about that, because there is a solution for this.

How do you call async method in constructor typescript?

async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic. setup(); constructor. typescript.


1 Answers

Don't do this in the constructor but in the loaded event of the window instead. You can mark the loaded eventhandler as async.

like image 67
Philip Stuyck Avatar answered Sep 28 '22 09:09

Philip Stuyck