Skip to content

Commit b52cff9

Browse files
committed
update
switched SpinLock to SemaphoreSlim
1 parent cea5dc8 commit b52cff9

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

src/BootstrapBlazor/Components/AutoComplete/AutoComplete.razor.cs

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
55

66
using Microsoft.Extensions.Localization;
7+
using System.Threading;
78

89
namespace BootstrapBlazor.Components;
910

@@ -128,9 +129,9 @@ private async Task OnClickItem(string val)
128129

129130
private List<string> Rows => _filterItems ?? [.. Items];
130131

131-
// In AutoComplete.razor.cs, add a tracking variable:
132+
// Thread-safe tracking using SemaphoreSlim for async compatibility
132133
private string _userCurrentInput = string.Empty;
133-
private SpinLock _spinLock = new SpinLock(false); // false for non-tracking mode
134+
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
134135

135136
/// <summary>
136137
/// TriggerFilter method
@@ -139,18 +140,17 @@ private async Task OnClickItem(string val)
139140
[JSInvokable]
140141
public override async Task TriggerFilter(string val)
141142
{
142-
// Update the current input with SpinLock protection
143-
bool lockTaken = false;
143+
// Thread-safe update using SemaphoreSlim
144+
await _semaphore.WaitAsync();
144145
try
145146
{
146-
_spinLock.Enter(ref lockTaken);
147147
_userCurrentInput = val;
148148
}
149149
finally
150150
{
151-
if (lockTaken) _spinLock.Exit();
151+
_semaphore.Release();
152152
}
153-
153+
154154
// Process filtering
155155
if (OnCustomFilter != null)
156156
{
@@ -169,30 +169,29 @@ public override async Task TriggerFilter(string val)
169169
: Items.Where(s => s.StartsWith(val, comparison));
170170
_filterItems = [.. items];
171171
}
172-
172+
173173
if (DisplayCount != null)
174174
{
175175
_filterItems = [.. _filterItems.Take(DisplayCount.Value)];
176176
}
177-
178-
// Check if still the latest input with SpinLock protection
177+
178+
// Thread-safe read using SemaphoreSlim
179+
await _semaphore.WaitAsync();
179180
string latestInput;
180-
lockTaken = false;
181181
try
182182
{
183-
_spinLock.Enter(ref lockTaken);
184183
latestInput = _userCurrentInput;
185184
}
186185
finally
187186
{
188-
if (lockTaken) _spinLock.Exit();
187+
_semaphore.Release();
189188
}
190-
189+
191190
// Only update CurrentValue if this is still the latest input
192191
if (latestInput == val)
193192
{
194193
CurrentValue = val;
195-
194+
196195
if (!ValueChanged.HasDelegate)
197196
{
198197
StateHasChanged();

0 commit comments

Comments
 (0)