Skip to content

Commit 0b73e57

Browse files
Copilotdanielgerlag
andcommitted
Fix StopAsync to properly await all running async tasks
Co-authored-by: danielgerlag <[email protected]>
1 parent 0509e6f commit 0b73e57

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/WorkflowCore/Services/BackgroundTasks/QueueConsumer.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ internal abstract class QueueConsumer : IBackgroundTask
2424
protected Task DispatchTask;
2525
private CancellationTokenSource _cancellationTokenSource;
2626
private Dictionary<string, EventWaitHandle> _activeTasks;
27+
private List<Task> _runningTasks;
28+
private readonly object _runningTasksLock = new object();
2729
private ConcurrentHashSet<string> _secondPasses;
2830

2931
protected QueueConsumer(IQueueProvider queueProvider, ILoggerFactory loggerFactory, WorkflowOptions options)
@@ -33,6 +35,7 @@ protected QueueConsumer(IQueueProvider queueProvider, ILoggerFactory loggerFacto
3335
Logger = loggerFactory.CreateLogger(GetType());
3436

3537
_activeTasks = new Dictionary<string, EventWaitHandle>();
38+
_runningTasks = new List<Task>();
3639
_secondPasses = new ConcurrentHashSet<string>();
3740
}
3841

@@ -115,6 +118,10 @@ private async Task Execute()
115118
_activeTasks.Add(item, waitHandle);
116119
}
117120
var task = ExecuteItem(item, waitHandle, activity);
121+
lock (_runningTasksLock)
122+
{
123+
_runningTasks.Add(task);
124+
}
118125
}
119126
catch (OperationCanceledException)
120127
{
@@ -138,6 +145,25 @@ private async Task Execute()
138145

139146
foreach (var handle in toComplete)
140147
handle.WaitOne();
148+
149+
// Also await all running tasks to ensure proper async completion
150+
Task[] tasksToAwait;
151+
lock (_runningTasksLock)
152+
{
153+
tasksToAwait = _runningTasks.ToArray();
154+
}
155+
156+
if (tasksToAwait.Length > 0)
157+
{
158+
try
159+
{
160+
await Task.WhenAll(tasksToAwait);
161+
}
162+
catch
163+
{
164+
// Individual task exceptions are already logged in ExecuteItem
165+
}
166+
}
141167
}
142168

143169
private async Task ExecuteItem(string itemId, EventWaitHandle waitHandle, Activity activity)

test/WorkflowCore.IntegrationTests/WorkflowCore.IntegrationTests.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
88
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
99
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
10-
<TargetFrameworks>net6.0;net8.0</TargetFrameworks>
10+
<TargetFrameworks>net6.0</TargetFrameworks>
1111
</PropertyGroup>
1212

1313
<ItemGroup>

0 commit comments

Comments
 (0)