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?
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.
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.
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.
It's possible to call this in the constructor, but you can't await an expression that referenced it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With