Skip to content

Commit 63714fa

Browse files
committed
Improved task execution flow.
1 parent dcbaf1e commit 63714fa

1 file changed

Lines changed: 12 additions & 11 deletions

File tree

TaskExecutor/TaskExecutor.cs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Collections.Concurrent;
2+
using System.Threading.Tasks;
23

34
namespace TaskExecutor;
45

@@ -122,21 +123,12 @@ private void StartProcessing()
122123
{
123124
while (!_internalCts.Token.IsCancellationRequested && !_externalCancellationToken.IsCancellationRequested)
124125
{
125-
await _semaphore.WaitAsync(_internalCts.Token).ConfigureAwait(false);
126-
127126
if (_taskQueue.TryDequeue(out var taskForExecute))
128127
{
129-
var task = ExecuteTaskAsync(taskForExecute);
130-
_taskRegistry.Add(task);
131-
_ = task.ContinueWith(t =>
132-
{
133-
_taskRegistry.Remove(t);
134-
_semaphore.Release();
135-
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
128+
_ = ExecuteTaskAsync(taskForExecute);
136129
}
137130
else
138131
{
139-
_semaphore.Release();
140132
await Task.Delay(50, _internalCts.Token).ConfigureAwait(false);
141133
}
142134
}
@@ -152,7 +144,16 @@ private async Task ExecuteTaskAsync(TaskForExecute taskForExecute)
152144
{
153145
try
154146
{
155-
await taskForExecute.TaskFunc().ConfigureAwait(false);
147+
await _semaphore.WaitAsync(_internalCts.Token).ConfigureAwait(false);
148+
149+
var task = taskForExecute.TaskFunc();
150+
_ = task.ContinueWith(t =>
151+
{
152+
_taskRegistry.Remove(t);
153+
_semaphore.Release();
154+
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
155+
_taskRegistry.Add(task);
156+
await task.ConfigureAwait(false);
156157
}
157158
catch (Exception ex)
158159
{

0 commit comments

Comments
 (0)