Skip to content

Commit ff42882

Browse files
committed
Improve SessionProcessor
1 parent 96c5280 commit ff42882

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/Kryptor.Client/SessionManager.cs

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public partial class SessionContainer
1313
private bool _cancellationRequested;
1414
private SessionGroup _sessionGroup;
1515
private readonly ConcurrentQueue<SessionHolder> _taskQueue = new ConcurrentQueue<SessionHolder>();
16+
private readonly HashSet<int> _taskSet = new HashSet<int>();
1617
private readonly List<Thread> _threads = new List<Thread>();
1718

1819
/// <summary>
@@ -232,25 +233,23 @@ public void StartQueuedSessions()
232233

233234
private void QueueProcessImpl()
234235
{
235-
int runningCount;
236236
List<SessionHolder> waiting;
237237

238238
if (_sessionGroup != null)
239239
{
240-
runningCount = _sessionGroup.Running;
241240
waiting = _sessionGroup.WaitingSessions;
242241
}
243242
else
244243
{
245-
runningCount = Holders.Count(x => x.Session.Status == SessionStatus.Running);
246244
waiting = Holders.Where(x => x.Session.Status == SessionStatus.NotStarted && SafeIsReady(x)).ToList();
247245
}
248246

249-
if (waiting.Count == 0 || runningCount >= MaxRunningSessions) return;
250-
251247
foreach (var sessionHolder in waiting)
252248
{
253-
_taskQueue.Enqueue(sessionHolder);
249+
if (_taskSet.Add(sessionHolder.Id))
250+
{
251+
_taskQueue.Enqueue(sessionHolder);
252+
}
254253
}
255254
}
256255

@@ -262,11 +261,20 @@ private void ProcessTasks()
262261
{
263262
try
264263
{
264+
if (sessionHolder.Session.Status != SessionStatus.NotStarted)
265+
{
266+
continue;
267+
}
268+
265269
StartManagedSession(sessionHolder);
266270
}
267271
catch (Exception ex)
268272
{
269-
sessionHolder.Session.Messages.Add("Error in session start: " + ex.Message);
273+
// Log the exception if verbose mode is enabled
274+
if (_sessionHost.Verbose)
275+
{
276+
Console.WriteLine($"Error starting session: {ex.Message}");
277+
}
270278
}
271279
}
272280
else
@@ -295,13 +303,18 @@ private void StartManagedSession(SessionHolder sessionHolder)
295303
{
296304
task.ContinueWith(t =>
297305
{
306+
lock (_lock)
307+
{
308+
_taskSet.Remove(sessionHolder.Id);
309+
}
310+
311+
if (sessionHolder.AutoRemove)
312+
{
313+
Remove(sessionHolder.Id);
314+
}
315+
298316
StartQueuedSessions();
299317
});
300-
301-
if (sessionHolder.AutoRemove)
302-
{
303-
task.ContinueWith(t => Remove(sessionHolder.Id));
304-
}
305318
}
306319
}
307320
}

0 commit comments

Comments
 (0)