简体   繁体   English

在没有等待的情况下调用异步方法会发生什么?

[英]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. 我想知道如果我在没有使用await的情况下调用标记为async的方法会发生什么。 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. 我知道这会产生编译警告,但我的问题是,如果在Initialize()中等待的方法调用仍然可以像预期的那样工作。 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. 正如您所看到的那样,setter不需要等待Initialize(),因为没有返回值,它是属性的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. 我想这样做的原因是我想将MVVM和数据后端结合起来,迫使我使用异步方法。

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. 我想将列表的当前选定条目绑定到DataId,每当用户更改选择时,它都会更新详细信息视图。 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). 当然,可以从事件处理程序执行异步方法调用,但为了更清晰的MVVM实现(主要使用数据绑定),我想避免使用事件处理程序。

If you call an async Task method without awaiting the task, then any exceptions from that method will be silently ignored. 如果在不等待任务的情况下调用async Task方法,则将以静默方式忽略该方法的任何异常。 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. 如果你调用async void方法(你在问题标题中提到,但你的代码没有这样做),那么将在SynchronizationContext上重新引发该方法的任何异常 - 在这种情况下,直接发送到UI主循环。

I have a blog post on asynchronous properties. 我有关于异步属性的博客文章 The last section introduces the NotifyTaskCompletion type , which was designed specifically for asynchronous data-binding. 最后一节介绍NotifyTaskCompletion类型 ,该类型专为异步数据绑定而设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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