简体   繁体   中英

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM