Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call async method in constructor?

I used to call async methods (fire and forgot?) in constructors by

 Task.Run(async () => await CallAsync());

I heard it's better to use ICommand to execute it.

ICommand MyCmd => new Command(async () => await CallAsync());

public MyClass()
{
     MyCmd.Execute(null);
}

What's the difference between these two methods?

like image 483
ca9163d9 Avatar asked Nov 21 '18 05:11

ca9163d9


People also ask

Can you call async method in constructor?

The problem arises when you're trying to call such an asynchronous method from a class constructor: you can't use the await keyword inside the constructor. As long as you're only using methods which don't return a value, you can get away with it by just calling them without await, but that's not the right way to do it.

Can constructor be async in TypeScript?

To create an async constructor functions in TypeScript, we can create a factory method. to create the MyClass class that has a private constructor. We use it to create a MyClass instance inside the CreateAsync function. The function is static so we don't need to instantiate MyClass to call it.

Can a constructor be async JS?

The static async factory function pattern allows us to emulate asynchronous constructors in JavaScript. At the core of this pattern is the indirect invocation of constructor . The indirection enforces that any parameters passed into the constructor are ready and correct at the type-level.

Can we use await in constructor C#?

It's possible to call this in the constructor, but you can't await an expression that referenced it.


1 Answers

Your post makes not much sense.

If you want to fire-and-forget an async method, then just calling it directly is enough.

public Task RunAsync() { }

public Constructor()
{
    RunAsync(); // fire-and-forget by not awaiting and ignoring returned task
}

There is no need to use Task.Run or Command, which technically does nothing on top of running the method.

But this kind of fire-and-forget code is frowned upon, because it makes testing of the code difficult. And starting such code in constructor makes the object creation have unexpected side-effects that are not immediately obvious. It is recommended to have some kind of Initialize method that can be called.

Another issue is that if the method causes an exception, a special handler must be register, otherwise it crashes whole application.

like image 112
Euphoric Avatar answered Oct 10 '22 02:10

Euphoric