忽略异步方法中的异常

Ignore an exception in an async method

我正在编写一个需要执行一些异步方法的应用程序 (.Net 5)。首先它创建一个 Job,然后它在作业中创建一个 Task,然后等待 Task 完成,最后删除 Job。对于上下文,这些是 Azure Batch 作业和任务,但我提到它只是为了表明我所说的任务不是 .Net 框架任务,而是一个普通的 class 恰好被命名为那个。除此之外,这与 Azure Batch 相关没有任何区别。

我编写了此方法来执行这些步骤:

    private async Task ExecuteTask(string jobName, string taskName, CloudTask task)
    {
      string poolName = ConfigurationManager.AppSettings["PoolName"];
      await taskScheduler.QueueBatchJob(poolName, jobName);
      await taskScheduler.QueueBatchTask(jobName, task);
      taskScheduler.WaitForTaskToComplete(jobName, taskName);
      _ = this.taskScheduler.DeleteJob(jobName); // I am intentionally not awaiting here
    }

调用方法有一个 try / catch,带有可能需要一段时间才能执行的额外代码。 我故意不等待 DeleteJob 方法,因为我不需要完成该方法才能继续,而且我也不在乎它是否失败。它在那里用于清理,但稍后可能会有另一个进程进行适当的清理。

现在,我的问题是,如果该方法确实存在错误,会发生什么情况?如果父方法没有完成,它会被父 try/catch 捕获吗?我绝对不想这样,如果是这样,我怎么能忽略它呢?

我将简单地引用 here:

中的一些引文来回答这个问题

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

在同一篇文章的后面

When you await a Task, the first exception is re-thrown, so you can catch the specific exception type (such as InvalidOperationException).

这基本上意味着: 该方法返回的 Task 将包含 Exception 但它只会在您 await 时引发。因此,不等待 Task 会导致所有异常都被 Task 对象吞没。