Skip to content

Commit aa800c6

Browse files
committed
More elegantly handle command timeout when run with lifecycle
1 parent 4442667 commit aa800c6

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/InEngine.Core/AbstractCommand.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
namespace InEngine.Core;
1111

12+
using System.Threading;
1213
using Microsoft.Extensions.Logging;
1314

1415
public abstract class AbstractCommand : IJob, IConsoleWrite, IHasCommandLifeCycle, IHasMailSettings
@@ -54,9 +55,16 @@ public virtual async Task RunWithLifeCycle()
5455
await RunAsync();
5556
else
5657
{
57-
var task = Task.Run(RunAsync);
58-
if (!task.Wait(TimeSpan.FromSeconds(SecondsBeforeTimeout)))
59-
throw new Exception($"Scheduled command timed out after {SecondsBeforeTimeout} second(s).");
58+
var timeoutSignal = new CancellationTokenSource(TimeSpan.FromSeconds(SecondsBeforeTimeout));
59+
try
60+
{
61+
await RunAsync().WaitAsync(timeoutSignal.Token).ConfigureAwait(false);
62+
}
63+
catch (OperationCanceledException)
64+
{
65+
throw new CommandFailedException(
66+
$"Scheduled command timed out after {SecondsBeforeTimeout} second(s).");
67+
}
6068
}
6169

6270
CommandLifeCycle.FirePostActions(this);

0 commit comments

Comments
 (0)