在异步方法中尝试 Catch

时间:2021-02-10 14:06:02

标签: c# winforms

大家好,我在下一段代码中有一个问题 await Task.Run(() => adapter.Fill(dataTable)); 如果它失败了 try catch 块不处理异常。我如何捕捉异常?

谢谢。

public async Task<DataTable> GetUsersAsync()
    {
        using (SqlConnection sqlConnection = new SqlConnection(GetSettingsConenction()))
        {
            try
            {
                await sqlConnection.OpenAsync();
                string query = "SELECT [dbo].[User].[usr_id] AS \"ID\", [dbo].[User].[usr_alias] AS \"ALIAS\", [dbo].[User].[usr_firstname] AS \"NOMBRE\", [dbo].[User].[usr_lastname] AS \"APELIIDO\", [dbo].[User].[usr_email] AS \"MAIL\", (SELECT [dbo].[UserRole].[uro_name] FROM [dbo].[UserRole] WHERE [dbo].[UserRole].[uro_id] LIKE [dbo].[User].usr_urol_id) AS \"ROL\" FROM [dbo].[User] WHERE [dbo].[User].[usr_deleted] NOT LIKE '1'";
                SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
                sqlCommand.CommandType = System.Data.CommandType.Text;
                sqlCommand.CommandTimeout = SQL_TIMEOUT_EXECUTION_COMMAND;

                SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand);
                DataTable dataTable = new DataTable();
                await Task.Run(() => adapter.Fill(dataTable));
                sqlConnection.Close();
                return dataTable;
            }
            catch
            {
                sqlConnection.Close();
                return null;
            }
        }
    }

编辑: enter image description here

打开连接后,我模拟互联网连接丢失,当它托盘填充数据表时,异常出现。说超时异常

1 个答案:

答案 0 :(得分:2)

实际问题

您向我们展示的这段代码实际上确实处理了 await Task.Run(() => adapter.Fill(dataTable));

引发的错误

只要您await async 方法,exception 就会被周围的 try catch 块捕获。

另请参考这个小样本https://dotnetfiddle.net/PwLEPD

使用 vs try catch

由于您已经在 SqlConnection 语句中声明了 using,因此无论如何都会正确关闭/处置连接。

using 块基本上是一个 try finally,它处理 using 中声明的所有资源。 close 中的 catch block 后面是 dispose 的自动 close(包括 using)。

关于截图

您的调试器在抛出异常时停止。这并不意味着您的 catch 块不会被击中。在里面设置一个断点,你会发现,按继续后,你会命中它。