如何最好地在 C# 中对永无止境的任务实施看门狗?
How to best implement a watchdog on a neverending task in C#?
我有一项服务,在其核心,运行通过调用以下方法进行一些无休止的循环:
public async Task DoStuffPeriodically(CancellationToken token);
它们是通过调用调用的:
var tokenSource = new CancellationTokenSource();
var stuffTask = DoStuffPeriodically(tokenSource.token);
现在,这将永远 运行,只有当我们在不同的方法上取消令牌并调用 stuffTask.Wait()
时才会停止。 只有这样 我们才能得到 DoStuffPeriodically 可能已经处理的任何异常。
DoStuffPeriodically 有可能(但不太可能)实际抛出,这意味着我指望的循环不再是 运行ning。我计划通过在主线程中有一个循环来监视它,该循环定期检查 stuffTask.IsFaulted
并抛出异常(这将强制服务重新启动)。
有更好的方法吗?如果有任何我不知道的回调,我不想轮询任务状态。
谢谢!
您可以使用 Task.ContinueWith,将 TaskContinuationOptions.OnlyOnFaulted
传递给 continuationOptions
参数。仅当前提抛出未处理的异常时,这才会触发回调。在此回调中,您可以设置一些标志或抛出异常。
stuffTask.ContinueWith(t => { throw new Exception(); },
null,
TaskContinuationOptions.OnlyOnFaulted);
我有一项服务,在其核心,运行通过调用以下方法进行一些无休止的循环:
public async Task DoStuffPeriodically(CancellationToken token);
它们是通过调用调用的:
var tokenSource = new CancellationTokenSource();
var stuffTask = DoStuffPeriodically(tokenSource.token);
现在,这将永远 运行,只有当我们在不同的方法上取消令牌并调用 stuffTask.Wait()
时才会停止。 只有这样 我们才能得到 DoStuffPeriodically 可能已经处理的任何异常。
DoStuffPeriodically 有可能(但不太可能)实际抛出,这意味着我指望的循环不再是 运行ning。我计划通过在主线程中有一个循环来监视它,该循环定期检查 stuffTask.IsFaulted
并抛出异常(这将强制服务重新启动)。
有更好的方法吗?如果有任何我不知道的回调,我不想轮询任务状态。
谢谢!
您可以使用 Task.ContinueWith,将 TaskContinuationOptions.OnlyOnFaulted
传递给 continuationOptions
参数。仅当前提抛出未处理的异常时,这才会触发回调。在此回调中,您可以设置一些标志或抛出异常。
stuffTask.ContinueWith(t => { throw new Exception(); },
null,
TaskContinuationOptions.OnlyOnFaulted);