簡體   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