📜  C#6.0 Await in catch/finally blocks

📅  最后修改于: 2020-11-01 03:17:49             🧑  作者: Mango

C#支持在catch/finally语句块使用await语句

C#await是关键字。它用于挂起方法的执行,直到完成等待的任务。

在C#6.0中,Microsoft添加了一项新功能,该功能使我们可以在catch或finally块内使用await。因此,我们可以在发生异常时执行异步任务。

让我们来看一个例子。在这里,我们在catch块内调用异步方法。

await in Catch Block示例

using System;
using System.Threading.Tasks;
using System.IO;
using static System.Console;
namespace CSharpFeatures
{
    public class ExceptionAwait
    {
        public static void Main(string[] args)
        {           
            addAsync();
        }
        async static Task addAsync()
        {
            try
            {
                int[] arr = new int[5];
                arr[10] = 12;
            }
            catch(Exception e) {
                // Using await in catch block
                await ExceptionOccured();
            }
        }
        async static Task ExceptionOccured()
        {
           Console.WriteLine("Array Exception Occurred");
        } 
    }
}

输出量

Array Exception Occurred

我们也可以在finally块中使用await。让我们来看一个例子。

C#在finally块示例中等待

using System;
using System.Threading.Tasks;
using System.IO;
using static System.Console;
namespace CSharpFeatures
{
    public class ExceptionAwait
    {
        public static void Main(string[] args)
        {
            addAsync();
        }
        async static Task addAsync()
        {
            try
            {
                int[] arr = new int[5];
                arr[10] = 12;
            }
            catch (Exception e)
            {
                // Using await in catch block
                await ExceptionOccured();
            }
            finally
            {
                // Using await in finally block
                await ReleasingResources();
            }
        }
        async static Task ExceptionOccured()
        {
            Console.WriteLine("Array Exception Occurred");
        }
        async static Task ReleasingResources()
        {
            Console.WriteLine("Resources has been released");
        }
    }
}

输出量

Array Exception Occurred
Resources has been released