我无法使用try-catch

时间:2019-11-30 08:36:25

标签: c# winforms

我尝试使用try-catch捕获SqlException,所以我编写了这段代码:

public async Task Open()
    {
        try
        {
            if (sqlconnection.State != ConnectionState.Open)
            {
                await Task.Run(() => sqlconnection.OpenAsync()).ConfigureAwait(false);

            }
        }
        catch(SqlException ec)
        {
          XtraMessageBox.Show(ec.Message);
        }
    }
public async Task<DataTable> SelectData(string stored_procedure, SqlParameter[] param)
    {

        using (SqlCommand sqlcmd = new SqlCommand())
        {

            if (string.IsNullOrEmpty(stored_procedure))
            {
                return null;
            }

            sqlcmd.CommandType = CommandType.StoredProcedure;
            sqlcmd.CommandText = stored_procedure;
            sqlcmd.Connection = sqlconnection;

            if (param != null)
            {
                sqlcmd.Parameters.AddRange(param);
            }

            using (DataTable dt = new DataTable())
            {
                using (SqlDataAdapter da = new SqlDataAdapter(sqlcmd))
                {
                    try
                    {
                        await Task.Run(() => da.Fill(dt)).ConfigureAwait(false);
                    }
                    catch(SqlException ec)
                    {
                        XtraMessageBox.Show(ec.Message);
                    }
                }
                return dt;
            }
        }

    }

但是不幸的是,这没有用,并且总是在此消息中da.Fill(dt)上出现错误

  

Microsoft.Data.SqlClient.SqlException     HResult = 0x80131904     消息= SQL Server实例的最佳产品。可以从头到尾享用美食。正确确定实例性的位置以及正确的SQL Server配置后,自动连接程序的配置将有所不同。 (提供者:接口SQL的错误,错误:26-服务器/实例特定的本地化错误)     源=框架Microsoft SqlClient数据提供程序     堆栈跟踪:      在Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,布尔breakConnection,Action 1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, Boolean isFirstTransparentAttempt, SqlAuthenticationMethod authType, String certificate, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, Boolean useOriginalAddressInfo, Boolean disableTnir, SqlAuthenticationProviderManager sqlAuthProviderManager) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover, Boolean isFirstTransparentAttempt, Boolean disableTnir) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, DbConnectionPool pool, String accessToken, SqlClientOriginalNetworkAddressInfo originalNetworkAddressInfo, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource 1重试,DbConnectionOptions userOptions,DbConnectionInternal&连接)      在Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection,TaskCompletionSource 1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource 1重试,DbConnectionOptions userOptions)      在Microsoft.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource 1 retry) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource 1重试)      在Microsoft.Data.SqlClient.SqlConnection.Open()      在System.Data.Common.DbDataAdapter.FillInternal(DataSet数据集,DataTable []数据表,Int32 startRecord,Int32 maxRecords,字符串srcTable,IDbCommand命令,CommandBehavior行为)      在System.Data.Common.DbDataAdapter.Fill处(DataTable [] dataTables,Int32 startRecord,Int32 maxRecords,IDbCommand命令,CommandBehavior行为)      在System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)      在C:\ Users \ MBoua \ source \ repos \ SIM Windows7 \ Smart Industrial Management \ DAL \ DataAccessLayerV550.cs:line 116中的Smart_Industrial_Management.DAL.DataAccessLayerV550。<> c__DisplayClass6_1.b__0()      在System.Threading.Tasks.Task`1.InnerInvoke()      在System.Threading.Tasks.Task.Execute()

此异常最初是在此调用堆栈上抛出的:     Microsoft.Data.SqlClient.SqlInternalConnection.OnError(Microsoft.Data.SqlClient.SqlException,bool,System.Action)     Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(Microsoft.Data.SqlClient.TdsParserStateObject,bool,bool)     Microsoft.Data.SqlClient.TdsParser.Connect(Microsoft.Data.SqlClient.ServerInfo,Microsoft.Data.SqlClient.SqlInternalConnectionTds,bool,long,bool,bool,bool,bool,bool,Microsoft.Data.SqlClient.SqlAuthenticationMethod,字符串, Microsoft.Data.SqlClient.ServerCertificateValidationCallback,Microsoft.Data.SqlClient.ClientCertificateRetrievalCallback,bool,bool,Microsoft.Data.SqlClient.SqlAuthenticationProviderManager)     Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(Microsoft.Data.SqlClient.ServerInfo,字符串,System.Security.SecureString,布尔,Microsoft.Data.ProviderBase.TimeoutTimer,布尔,布尔,布尔)     Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(Microsoft.Data.SqlClient.ServerInfo,字符串,System.Security.SecureString,布尔,Microsoft.Data.SqlClient.SqlConnectionString,Microsoft.Data.SqlClient.SqlCredential,Microsoft.Data.ProviderBase。超时计时器)     Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(Microsoft.Data.ProviderBase.TimeoutTimer,Microsoft.Data.SqlClient.SqlConnectionString,Microsoft.Data.SqlClient.SqlCredential,字符串,System.Security.SecureString,布尔)     Microsoft.Data.SqlClient.SqlInternalConnectionTds.SqlInternalConnectionTds(Microsoft.Data.ProviderBase.DbConnectionPoolIdentity,Microsoft.Data.SqlClient.SqlConnectionString,Microsoft.Data.SqlClient.SqlCredential,对象,字符串,System.Security.SecureString,bool,Microsoft.Data。 SqlClient.SqlConnectionString,Microsoft.Data.SqlClient.SessionData,Microsoft.Data.SqlClient.ServerCertificateValidationCallback,Microsoft.Data.SqlClient.ClientCertificateRetrievalCallback,Microsoft.Data.ProviderBase.DbConnectionPool,字符串,Microsoft.Data.SqlClient.SqlClientOriginalNetworkAddressInfo,bool,Microsoft。 Data.SqlClient.SqlAuthenticationProviderManager)     Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(Microsoft.Data.Common.DbConnectionOptions,Microsoft.Data.Common.DbConnectionPoolKey,对象,Microsoft.Data.ProviderBase.DbConnectionPool,System.Data.Common.DbConnection,Microsoft.Data.Common。 DbConnectionOptions)     Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(Microsoft.Data.ProviderBase.DbConnectionPool,System.Data.Common.DbConnection,Microsoft.Data.Common.DbConnectionOptions,Microsoft.Data.Common.DbConnectionPoolKey,Microsoft.Data.Common.DbConnectionOptions)     Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(System.Data.Common.DbConnection,Microsoft.Data.Common.DbConnectionOptions,Microsoft.Data.ProviderBase.DbConnectionInternal)     ...     [通话堆栈被截断]

我以这种方式使用
我创建了一个名为CLS_VoortmanV550的类,并输入了以下代码:

public async Task<DataTable> GetV550Batch()
    {
        DAL.DataAccessLayerV550 DAL = new DAL.DataAccessLayerV550();

        using (DataTable dt = await Task.Run(() => DAL.SelectData("GetV550Batch", null)).ConfigureAwait(false))
        {
            DAL.Close();
            return dt;
        }
    }

从形式上讲,我将此方法称为

 try
        {
            gridControl3.DataSource = await clsV550.GetV550Batch().ConfigureAwait(true);
        }
        catch
        {
            XtraMessageBox.Show(Resources.FailedConnectV550, Resources.error, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

1 个答案:

答案 0 :(得分:0)

您永远不要在后台任务中进行用户界面交互。 而Task类的目的就是这样做。

您正在等待任务完成。 任务结束后,您可以检查

 Task.IsSuccessfullCompleted
 Task.IsCancelled

等 如果有例外,您将在这里找到例外。

 Task.AggregateException

https://docs.microsoft.com/de-de/dotnet/api/system.threading.tasks.task.exception?view=netframework-4.8

这将包含有关发生的异常的信息,可能是多个。

因此,通常不应在线程之间使用此try-catch-pattern。

如果您在Task中进行异常处理,请将其记录在某处,但不要附带MessagesBoxes。与用户交谈是前台线程的工作。