Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when calling an async method without await?

I wonder what happens if I call a method that is marked as async without using await. Consider this example:

private int id = 0;
async Task Initialize()
{
     var content = await LoadFromDisk(id);
     await Process(content);
     return;
}

DataId
{
    get { return id; }
    set { id = value; Initialize(); }
}

I know that this will produce a compile warning, but my question is if the awaited method calls in Initialize() will still work as one would expect. As you can see it is not necessary for the setter to await Initialize() as there is no return value and it's the last call of the property's setter. It's kind of fire and forget.

The reason I would like to do this is that I would like to combine MVVM and a data backend that forces me to use async methods.

In the example above, the user selects an entry from a list and the program should display detailed information about the entry in another part of the view.

I would like to bind the currently selected entry of the list to DataId, which updates the detail view whenever the user changes the selection. Of course, it would be possible to do the async method calls from an event handler but I would like to avoid event handlers for the sake of a cleaner MVVM implementation (using mostly databinding).

like image 380
SebastianR Avatar asked Feb 18 '14 16:02

SebastianR


People also ask

What happens when you call an async function?

Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then JavaScript automatically wraps it in a promise which is resolved with its value.

What happens when you don't await a promise?

The promise is rejected.

Can I call async function without await Python?

Add await keyword when you call your async functions (without it they won't run).

Can we call await without async?

You can use the await keyword on its own (outside of an async function) within a JavaScript module. This means modules, with child modules that use await , wait for the child module to execute before they themselves run, all while not blocking other child modules from loading.


1 Answers

If you call an async Task method without awaiting the task, then any exceptions from that method will be silently ignored. If you call an async void method (which you mention in your question title, but your code is not doing), then any exceptions from that method will be re-raised on the SynchronizationContext - in this case, sent directly to the UI main loop.

I have a blog post on asynchronous properties. The last section introduces the NotifyTaskCompletion type, which was designed specifically for asynchronous data-binding.

like image 82
Stephen Cleary Avatar answered Oct 02 '22 15:10

Stephen Cleary