Skip to content

Commit ab5324d

Browse files
SimonCroppCopilot
andauthored
avoid Lock acquisition on ErrorCount/WarningCount when no errors exist (dotnet#4157)
* avoid Lock acquisition on ErrorCount/WarningCount when no errors exist 1. _hasErrorOrWarning marked volatile (line 278) -- the field was already read without a lock at line 1212, so this makes the existing pattern and the new fast paths correct across all memory models. 2. ErrorCount fast path -- returns 0 immediately when _hasErrorOrWarning is false, skipping the lock. Safe because _hasErrorOrWarning is only set to false under the lock when _errors is also nulled. 3. WarningCount fast path -- same treatment. * Update src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update TdsParserStateObject.cs --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent bf9c17d commit ab5324d

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ private enum SnapshotStatus
275275
internal SqlErrorCollection _errors;
276276
internal SqlErrorCollection _warnings;
277277
internal object _errorAndWarningsLock = new object();
278-
private bool _hasErrorOrWarning;
278+
private volatile bool _hasErrorOrWarning;
279279

280280
// local exceptions to cache warnings and errors that occurred prior to sending attention
281281
internal SqlErrorCollection _preAttentionErrors;
@@ -2672,6 +2672,12 @@ internal int ErrorCount
26722672
{
26732673
get
26742674
{
2675+
if (!_hasErrorOrWarning &&
2676+
Volatile.Read(ref _errors) == null &&
2677+
Volatile.Read(ref _warnings) == null)
2678+
{
2679+
return 0;
2680+
}
26752681
int count = 0;
26762682
lock (_errorAndWarningsLock)
26772683
{
@@ -2713,6 +2719,10 @@ internal int WarningCount
27132719
{
27142720
get
27152721
{
2722+
if (!_hasErrorOrWarning && _warnings == null)
2723+
{
2724+
return 0;
2725+
}
27162726
int count = 0;
27172727
lock (_errorAndWarningsLock)
27182728
{

0 commit comments

Comments
 (0)