Skip to content

Commit e9e25a9

Browse files
KSemenenkoCopilot
andauthored
Update ManagedCode.Communication/Commands/Stores/MemoryCacheCommandIdempotencyStore.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 84e7dd3 commit e9e25a9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

ManagedCode.Communication/Commands/Stores/MemoryCacheCommandIdempotencyStore.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,45 @@ public Task<bool> TrySetCommandStatusAsync(string commandId, CommandExecutionSta
113113
SetCommandStatusAsync(commandId, newStatus, cancellationToken);
114114

115115
return Task.FromResult((currentStatus, true));
116+
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
117+
118+
public async Task<bool> TrySetCommandStatusAsync(string commandId, CommandExecutionStatus expectedStatus, CommandExecutionStatus newStatus, CancellationToken cancellationToken = default)
119+
{
120+
await _semaphore.WaitAsync(cancellationToken);
121+
try
122+
{
123+
var currentStatus = _memoryCache.Get<CommandExecutionStatus?>(GetStatusKey(commandId)) ?? CommandExecutionStatus.NotFound;
124+
125+
if (currentStatus == expectedStatus)
126+
{
127+
await SetCommandStatusAsync(commandId, newStatus, cancellationToken);
128+
return true;
129+
}
130+
131+
return false;
132+
}
133+
finally
134+
{
135+
_semaphore.Release();
136+
}
137+
}
138+
139+
public async Task<(CommandExecutionStatus currentStatus, bool wasSet)> GetAndSetStatusAsync(string commandId, CommandExecutionStatus newStatus, CancellationToken cancellationToken = default)
140+
{
141+
await _semaphore.WaitAsync(cancellationToken);
142+
try
143+
{
144+
var statusKey = GetStatusKey(commandId);
145+
var currentStatus = _memoryCache.Get<CommandExecutionStatus?>(statusKey) ?? CommandExecutionStatus.NotFound;
146+
147+
// Set new status
148+
await SetCommandStatusAsync(commandId, newStatus, cancellationToken);
149+
150+
return (currentStatus, true);
151+
}
152+
finally
153+
{
154+
_semaphore.Release();
116155
}
117156
}
118157

0 commit comments

Comments
 (0)