C# SQLServer关闭时,SqlConnection OpenAsync会阻止UI

C# SQLServer关闭时,SqlConnection OpenAsync会阻止UI,c#,sqlconnection,C#,Sqlconnection,我有一个简单的WPF客户端应用程序(.NET4.6.2),只有一个按钮。 SqlConnection.OpenAsync方法在执行以下步骤时阻止UI线程: SQL Server已启动并可从客户端访问 启动客户端应用程序 单击按钮=>UI未被阻止(如预期)=>消息框显示“确定” 关闭SQL Server 单击按钮=>UI被阻止-OpenAsync阻止UI=>消息框“显示”错误 再次单击按钮=>UI未再次被阻止=>消息框显示“错误” 仅当它从单击->成功转到单击->错误OpenAsync块UI线程时

我有一个简单的WPF客户端应用程序(.NET4.6.2),只有一个按钮。
SqlConnection.OpenAsync
方法在执行以下步骤时阻止UI线程:

  • SQL Server已启动并可从客户端访问
  • 启动客户端应用程序
  • 单击按钮=>UI未被阻止(如预期)=>消息框显示“确定”
  • 关闭SQL Server
  • 单击按钮=>UI被阻止-OpenAsync阻止UI=>消息框“显示”错误
  • 再次单击按钮=>UI未再次被阻止=>消息框显示“错误”
  • 仅当它从单击->成功转到单击->错误OpenAsync块UI线程时。 我错过了什么

    private async void按钮\u单击(对象发送方,路由目标)
    {
    尝试
    {
    使用(var conn=new SqlConnection(“..”))
    {
    等待连接OpenAsync();
    }
    }
    捕获(系统异常)
    {
    MessageBox.Show(“err”);
    返回;
    }
    MessageBox.Show(“ok”);
    }
    
    编辑:

    挂起期间暂停调试器时调用堆栈:

    System.Data.dll!SNINativeMethodWrapper.SNIOpenSyncEx(SNINativeMethodWrapper.ConsumerInfo consumerInfo, string constring, ref System.IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel, int transparentNetworkResolutionStateNo, int totalTimeout, bool isAzureSqlServerEndpoint)    Unknown
        System.Data.dll!System.Data.SqlClient.SNIHandle.SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, string serverName, byte[] spnBuffer, bool ignoreSniOpenTimeout, int timeout, out byte[] instanceName, bool flushCache, bool fSync, bool fParallel, System.Data.SqlClient.TransparentNetworkResolutionState transparentNetworkResolutionState, int totalTimeout)   Unknown
        System.Data.dll!System.Data.SqlClient.TdsParserStateObject.CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, byte[] spnBuffer, bool flushCache, bool async, bool fParallel, System.Data.SqlClient.TransparentNetworkResolutionState transparentNetworkResolutionState, int totalTimeout) Unknown
        System.Data.dll!System.Data.SqlClient.TdsParser.Connect(System.Data.SqlClient.ServerInfo serverInfo, System.Data.SqlClient.SqlInternalConnectionTds connHandler, bool ignoreSniOpenTimeout, long timerExpire, bool encrypt, bool trustServerCert, bool integratedSecurity, bool withFailover, bool isFirstTransparentAttempt, System.Data.SqlClient.SqlAuthenticationMethod authType, bool disableTnir, System.Data.SqlClient.SqlAuthenticationProviderManager sqlAuthProviderManager)  Unknown
        System.Data.dll!System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(System.Data.SqlClient.ServerInfo serverInfo, string newPassword, System.Security.SecureString newSecurePassword, bool ignoreSniOpenTimeout, System.Data.ProviderBase.TimeoutTimer timeout, bool withFailover, bool isFirstTransparentAttempt, bool disableTnir)  Unknown
        System.Data.dll!System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(System.Data.SqlClient.ServerInfo serverInfo, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance, System.Data.SqlClient.SqlConnectionString connectionOptions, System.Data.SqlClient.SqlCredential credential, System.Data.ProviderBase.TimeoutTimer timeout)    Unknown
        System.Data.dll!System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(System.Data.ProviderBase.TimeoutTimer timeout, System.Data.SqlClient.SqlConnectionString connectionOptions, System.Data.SqlClient.SqlCredential credential, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance) Unknown
        System.Data.dll!System.Data.SqlClient.SqlInternalConnectionTds.SqlInternalConnectionTds(System.Data.ProviderBase.DbConnectionPoolIdentity identity, System.Data.SqlClient.SqlConnectionString connectionOptions, System.Data.SqlClient.SqlCredential credential, object providerInfo, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance, System.Data.SqlClient.SqlConnectionString userConnectionOptions, System.Data.SqlClient.SessionData reconnectSessionData, System.Data.ProviderBase.DbConnectionPool pool, string accessToken, bool applyTransientFaultHandling, System.Data.SqlClient.SqlAuthenticationProviderManager sqlAuthProviderManager)    Unknown
        System.Data.dll!System.Data.SqlClient.SqlConnectionFactory.CreateConnection(System.Data.Common.DbConnectionOptions options, System.Data.Common.DbConnectionPoolKey poolKey, object poolGroupProviderInfo, System.Data.ProviderBase.DbConnectionPool pool, System.Data.Common.DbConnection owningConnection, System.Data.Common.DbConnectionOptions userOptions) Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(System.Data.ProviderBase.DbConnectionPool pool, System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions options, System.Data.Common.DbConnectionPoolKey poolKey, System.Data.Common.DbConnectionOptions userOptions)   Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionPool.CreateObject(System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal oldConnection)   Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal oldConnection)  Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionPool.TryGetConnection(System.Data.Common.DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, System.Data.Common.DbConnectionOptions userOptions, out System.Data.ProviderBase.DbConnectionInternal connection)   Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionPool.TryGetConnection(System.Data.Common.DbConnection owningObject, System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry, System.Data.Common.DbConnectionOptions userOptions, out System.Data.ProviderBase.DbConnectionInternal connection)    Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(System.Data.Common.DbConnection owningConnection, System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal oldConnection, out System.Data.ProviderBase.DbConnectionInternal connection)    Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(System.Data.Common.DbConnection outerConnection, System.Data.ProviderBase.DbConnectionFactory connectionFactory, System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry, System.Data.Common.DbConnectionOptions userOptions)  Unknown
        System.Data.dll!System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(System.Data.Common.DbConnection outerConnection, System.Data.ProviderBase.DbConnectionFactory connectionFactory, System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry, System.Data.Common.DbConnectionOptions userOptions)    Unknown
        System.Data.dll!System.Data.SqlClient.SqlConnection.TryOpenInner(System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry)  Unknown
        System.Data.dll!System.Data.SqlClient.SqlConnection.TryOpen(System.Threading.Tasks.TaskCompletionSource<System.Data.ProviderBase.DbConnectionInternal> retry)   Unknown
        System.Data.dll!System.Data.SqlClient.SqlConnection.OpenAsync(System.Threading.CancellationToken cancellationToken) Unknown
        System.Data.dll!System.Data.Common.DbConnection.OpenAsync() Unknown
    >   TestWpf.exe!TestWpf.UndoManagerTest.UndoManagerTestView.Button_Click(object sender, System.Windows.RoutedEventArgs e) Line 35   C#
        PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
        PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
        PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
        PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs e)  Unknown
        PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick()   Unknown
        PresentationFramework.dll!System.Windows.Controls.Button.OnClick()  Unknown
        PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)    Unknown
        PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)  Unknown
        PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
        PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
        PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
        PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
        PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent)  Unknown
        PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)    Unknown
        PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
        PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
        PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
        PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
        PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
        PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args)    Unknown
        PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) Unknown
        PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
        PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)  Unknown
        PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)   Unknown
        PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)   Unknown
        PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)   Unknown
        PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)    Unknown
        WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
        WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
        WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
        WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
        WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
        WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam)  Unknown
        [Native to Managed Transition]  
        [Managed to Native Transition]  
        WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame)   Unknown
        WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame)   Unknown
        PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)   Unknown
        PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)  Unknown
        PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window)  Unknown
        PresentationFramework.dll!System.Windows.Application.Run()  Unknown
        TestWpf.exe!TestWpf.App.Main() Line 53  C#
    
    System.Data.dll!SNINativeMethodWrapper.SNIOpenSyncEx(SNINativeMethodWrapper.ConsumerInfo ConsumerInfo,字符串分析,ref System.IntPtr pConn,byte[]spnBuffer,byte[]instanceName,bool fOverrideCache,bool fSync,int timeout,bool fParallel,int transparentNetworkResolutionStateNo,int totalTimeout,bool isAzureSqlServerEndpoint)未知
    System.Data.dll!System.Data.SqlClient.SNIHandle.SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo,string serverName,byte[]spnBuffer,bool ignoresInOpenTimeout,int timeout,out byte[]instanceName,bool flushCache,bool fSync,bool fParallel,System.Data.SqlClient.TransparentNetworkResolutionState TransparentNetworkResolutionState TransparentNetworkResolutionState,int totalTimeout)不为人知
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.CreatePhysicalSNIHandle(字符串服务器名、bool IgnoresInOpenTimeout、long-TimerSpire、out字节[]instanceName、字节[]spnBuffer、bool flushCache、bool异步、bool fParallel、System.Data.SqlClient.TransparentNetworkResolutionState TransparentNetworkResolutionState、int totalTimeout)未知
    System.Data.dll!System.Data.SqlClient.TdsParser.Connect(System.Data.SqlClient.ServerInfo ServerInfo,System.Data.SqlClient.SqlInternalConnectionDS connHandler,bool IgnoresInOpenTimeout,long-TimerPire,bool encrypt,bool trustServerCert,bool integratedSecurity,bool withFailover,bool IsFirstTransparentAttest,System.Data.SqlClient.SqlAuthenticationMethod authType,bool disableTnir,System.Data。SqlClient.SqlAuthenticationProviderManager(sqlAuthProviderManager)未知
    System.Data.dll!System.Data.SqlClient.SqlInternalConnectionDS.AttemptOneLogin(System.Data.SqlClient.ServerInfo ServerInfo,string newPassword,System.Security.SecureString newSecurePassword,bool IgnoresInOpenTimeout,System.Data.ProviderBase.TimeoutTimer timeout,bool withFailover,bool IsFirstTransparentTest,bool disableTnir)未知
    System.Data.dll!System.Data.SqlClient.sqlinternalconnectionds.LoginNoFailover(System.Data.SqlClient.ServerInfo ServerInfo、string newPassword、System.Security.SecureString newSecurePassword、bool redirectedUserInstance、System.Data.SqlClient.SqlConnectionString连接选项、System.Data.SqlClient.SqlCredential凭据、System.Data.ProviderBase.TimeoutTimer超时)未知
    System.Data.dll!System.Data.SqlClient.SqlInternalConnectionDS.OpenLoginList(System.Data.ProviderBase.TimeoutTimer超时,System.Data.SqlClient.SqlConnectionString连接选项,System.Data.SqlClient.SqlCredential凭据,string新密码,System.Security.SecureString newSecurePassword,bool redirectedUserInstance)未知
    System.Data.dll!System.Data.SqlClient.sqlinternalconnectionds.sqlinternalconnectionds(System.Data.ProviderBase.DbConnectionPoolIdentity、System.Data.SqlClient.SqlConnectionString连接选项、System.Data.SqlClient.SqlCredential凭据、对象providerInfo、字符串newPassword、System.Security.SecureString newSecurePassword、bool redirectedUserInstance、System.Data.SqlClient.SqlConnectionString userConnectionOptions、System.Data.SqlClient.SessionData重新连接SessionData、System.Data.ProviderBase.DbConnectionPool池、string accessToken、bool applyTransientFaultHandling、System.Data.SqlClient.SqlAuthenticationProviderManager sqlAuthProviderManager)未知
    System.Data.dll!System.Data.SqlClient.SqlConnectionFactory.CreateConnection(System.Data.Common.DbConnectionOptions选项,System.Data.Common.DbConnectionPoolKey poolKey,object poolGroupProviderInfo,System.Data.ProviderBase.DbConnectionPool池,System.Data.Common.DbConnection owningConnection,System.Data.Common.DbConnectionOptions用户选项)未知
    System.Data.dll!System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(System.Data.ProviderBase.DbConnectionPool池,System.Data.Common.DbConnectionOwningObject,System.Data.Common.DbConnectionOptions选项,System.Data.Common.DbConnectionPoolKey poolKey,System.Data.Common.DbConnectionOptions用户选项)未知
    System.Data.dll!System.Data.ProviderBase.DbConnectionPool.CreateObject(System.Data.Common.DbConnection owningObject、System.Data.Common.DbConnectionOptions用户选项、System.Data.ProviderBase.DbConnectionInternal oldConnection)未知
    System.Data.dll!System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(System.Data.Common.DbConnection owningObject、System.Data.Common.DbConnectionOptions userOptions、System.Data.ProviderBase.DbConnectionInternal oldConnection)未知
    System.Data.dll!System.Data.ProviderBase.DbConnectionPool.TryGetConnection(System.Data.Common.DbConnection owningObject,uint WaitForMultipleObjectStimOut,bool allowCreate,bool OnlyonEckConnection,System.Data.Common.DbConnectionOptions用户选项,out System.Data.ProviderBase.DbConnection内部连接)
    
    Task.Run(async () => ... await connection.OpenAsync() ...);
    
    using (var conn = new SqlConnection("...."))   
    {
        await conn.OpenAsync().ConfigureAwait(false);
    }
    
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await Task.Run(async () =>
            {
                try
                {
                    using (var conn = new SqlConnection("...."))
                    {
                        await conn.OpenAsync();
                    }
                }
                catch (System.Exception)
                {
                    MessageBox.Show("err");
                    return;
                }
                MessageBox.Show("ok");
            }
        );
    }
    
    await Task.Run(async () => await conn.OpenAsync());