繁体   English   中英

C# SQLConnection.Open() 挂起,无一例外

[英]C# SQLConnection.Open() hangs, with no exception

I am using C# in Visual Studio 2019, with Xamarin.Forms, and SQl in SSMS 2018 and have the below code (where [] is used to replace unneccessary information)

try
{
  using(SqlConnection connection = new SqlConnection())
  {
     connection.ConnectionString = "Server=[ServerName]; Database=[DatabaseName]; User Id= [UserID]; Password=[Password]";

     connection.Open();

     SqlCommand command = new SqlCommand("SELECT * from [TableName]", connection);

     [Does stuff here]
  }
}
catch (Exception ex)
{
  System.Diagnostics.Debug.WriteLine(ex)
}

当我运行它时,它无限期地挂在connection.Open() 调试模式继续运行并似乎从Connection.Open()继续,但从未到达下一行。

我尝试过使用不同版本的 ConnectionString,使用不同的数据库并使用Trusted_Connection=true而不是指定用户名和密码,但它们没有任何区别。 Connection Timeout = 5添加到 connectionString 无效。

我相信这可能是我在 SQL 中的设置的问题,但是由于我是新手,所以我不知道从哪里开始,并且我检查过的类似论坛帖子已经按照Connection Timeout ( Connection.open for无限期挂起,不抛出异常)或从未得到回答。

任何建议将不胜感激。

您可以使用连接字符串中的凭据登录 SSMS 吗?

否则我很幸运确保连接尚未打开或断开:

if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
{
    connection.Open();
}

您可以尝试按以下方式更改代码行吗-

connection.ConnectionString = "数据源=[ServerName];初始目录=[DatabaseName];集成安全=SSPI;"

解决此问题的方法是传入取消令牌实例,如下所示,

public async Task<IEnumerable<Toy>> ShowToybox(CancellationToken t)
{
   // notice I turned this into an async operation. 
   // Reason is to let this operation to find its way out if something happens
    var connString = "Server=xyz; Connection Timeout=250";
    //Timeout might not happen, if that is not the case see below..
    using(SqlConnection connection = new SqlConnection(connString))
    {
        if ( t.IsCancellationRequested) {
            t.ThrowIfCancellationRequested();
        }
       // await query here. To fetch records from the toybox table
       return matches;
     }

主要问题是您不能信任连接。State

为了让这个工作,使用这个方法的代码应该期望 go 错误。

class Program
{
   static void Main()
  {
      var box = new ToxBox(); //it has method shown above
      var s = new CancellationTokenSource();
      s.CancelAfter(400); //it prevents method from hanging
      var task = Task.Run(() = box.ShowToybox(s.Token));
      try
      {
          task.Wait(s.Token);
          var myToys = task.Result();
          Console.WriteLine($"I have {myToys.Count()} toys");
      }
      catch (Exception e)
      {
          Console.WriteLine("Something happened!"); 
      }
      finally
      {
          s.Dispose(); //this is important
      }  
  }
}

请参阅https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM