此代码有什么问题?
我总是得到一个
异常(exception)
System.Threading.Monitor.Exit(m_sqlConnection)
但是...将Monitor语句放在try-catch-finally块的内部还是外部都没关系,无论如何,我总是会遇到此异常。
也就是说,在我编译代码之后。
如果在遇到第一个异常后让它再次运行,它会正常工作...
总是在重新编译之后...
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/