调用异步方法时没有等待会发生什么? [英] What happens when calling an async method without await?

查看:165
本文介绍了调用异步方法时没有等待会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果我叫标记为异步,而无需使用的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(); }
}

我知道,这将产生一个编译警告,但我的问题是,如果期待已久的方法调用初始化()将仍然工作的人们所期望的。正如你可以看到它是没有必要的二传手等待初始化()因为没有返回值和它的属性的setter的最后一次通话。这是一种火,忘记了。

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.

我想这样做的原因是,我想MVVM并迫使我采用异步方法数据的后端相结合。

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.

我想列表来DATAID当前的选择项,这将更新每当用户更改选择详细视图进行绑定。当然,也有可能从事件处理函数中执行异步方法调用,但我想避免的事件处理程序更清洁MVVM实现的缘故(主要使用数据绑定)。

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

推荐答案

如果你调用不必等待任务的异步任务方法,然后从该方法的任何异常会忽略。如果你调用一个异步无效办法(你在你的问题标题中提到,但你的code是的的那样),那么任何异常从该方法将在的SynchronizationContext 重新升高。 - 在这种情况下,直接发送到UI主循环

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.

我对异步特性的博客文章。的最后一节介绍在<一个href=\"https://nitoasyncex.$c$cplex.com/wikipage?title=NotifyTaskCompletion\"><$c$c>NotifyTaskCompletion键入,它是专门用于异步数据绑定。

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

这篇关于调用异步方法时没有等待会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆