gpt4 book ai didi

c# - 为什么这段代码总是得到 SynchronizationLockException?

转载 作者:太空狗 更新时间:2023-10-30 00:34:51 26 4
gpt4 key购买 nike

这段代码有什么问题?

我总是得到一个

Object synchronization method was called from an unsynchronized block of code

异常(exception)情况

System.Threading.Monitor.Exit(m_sqlConnection)

但是...无论我将 Monitor 语句放在 try-catch-finally-block 的内部还是外部,以任何组合,我总是会遇到此异常。

也就是我编译代码之后。如果我在得到第一个异常后让它再次运行,它工作正常......总是在重新编译之后...

Public Shared Function GetDataTable(ByRef strSQL As String, ByRef dt As System.Data.DataTable, Optional ByRef strTableName As String = "ThisTable") As Integer
Dim daQueryTable As System.Data.SqlClient.SqlDataAdapter = Nothing



Try
System.Threading.Monitor.TryEnter(m_sqlConnection, 5000)

If isDataBaseConnectionOpen() = False Then OpenSQLConnection()


daQueryTable = New System.Data.SqlClient.SqlDataAdapter(strSQL, m_sqlConnection)
dt = New System.Data.DataTable(strTableName)

daQueryTable.Fill(dt)
Catch ex As Exception
Log(ex)
Return -1
Finally
m_sqlConnection.Close()
System.Threading.Monitor.Exit(m_sqlConnection)
daQueryTable.Dispose()
daQueryTable = Nothing
End Try

Return dt.Rows.Count
End Function ' GetDataTable

C#版本:

public static int GetDataTable(ref string strSQL, ref System.Data.DataTable dt, ref string strTableName = "ThisTable")
{
System.Data.SqlClient.SqlDataAdapter daQueryTable = null;



try {
System.Threading.Monitor.TryEnter(m_sqlConnection, 5000);

if (isDataBaseConnectionOpen() == false)
OpenSQLConnection();


daQueryTable = new System.Data.SqlClient.SqlDataAdapter(strSQL, m_sqlConnection);
dt = new System.Data.DataTable(strTableName);

daQueryTable.Fill(dt);
} catch (Exception ex) {
Log(ex);
return -1;
} finally {
m_sqlConnection.Close();
System.Threading.Monitor.Exit(m_sqlConnection);
daQueryTable.Dispose();
daQueryTable = null;
}

return dt.Rows.Count;
} // GetDataTable

最佳答案

您正在调用 TryEnter ,但忽略结果 - 所以即使您不拥有它,您也会尝试退出监视器。如果 TryEnter 返回 false,您应该采取适当的措施,例如退出该方法。

关于c# - 为什么这段代码总是得到 SynchronizationLockException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6382569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com