Skip to content

Instantly share code, notes, and snippets.

@in-async
Last active August 10, 2022 11:37
Show Gist options
  • Save in-async/57e02d4f36dbb6eff9bf4a174b42c784 to your computer and use it in GitHub Desktop.
Save in-async/57e02d4f36dbb6eff9bf4a174b42c784 to your computer and use it in GitHub Desktop.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace Commons {
/// <summary>
/// <see cref="BackgroundService.ExecuteAsync(CancellationToken)"/> で生じた例外が全て Host でハンドルされるよう対応した <see cref="BackgroundService"/> 。
/// </summary>
/// <remarks>
/// <para>
/// <see cref="BackgroundService.ExecuteAsync(CancellationToken)"/> が完了済みタスクを返す時、
/// <see cref="BackgroundService.StartAsync(CancellationToken)"/> は明らかにセマンティクスの異なるそれを自身のタスクとして返す実装になっている。
/// ref. https://github.com/dotnet/runtime/blob/a3fb0d383adf98ee2fb2ab816c28735dc1caaba0/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs#L44-L50
/// </para>
/// <para>
/// その為、 <see cref="BackgroundService.ExecuteAsync(CancellationToken)"/> 内で await 前に例外が生じた場合は Unhandled exception になり、
/// await 後に例外が生じた場合は Host にハンドルされるという、一貫性のない状態となっている。
/// ref. https://github.com/dotnet/runtime/issues/36388#issuecomment-706217317
/// </para>
/// <para>
/// <see cref="ImprovedBackgroundService"/> は <see cref="StartAsync(CancellationToken)"/> にて <see cref="BackgroundService.ExecuteTask"/> を返さないよう対応した。
/// </para>
/// </remarks>
public abstract class ImprovedBackgroundService : BackgroundService {
public override Task StartAsync(CancellationToken cancellationToken) {
base.StartAsync(cancellationToken);
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment