C# Prism – BackgroundService 생성하기

By | 2024년 10월 31일
Table of Contents

C# Prism – BackgroundService 생성하기

놀랍게도 인공지능이 코딩한 코드입니다.

public interface IBackgroundService
{
    Task StartAsync();
    Task StopAsync();
}

public class BackgroundService : IBackgroundService
{
    private readonly CancellationTokenSource _cts = new CancellationTokenSource();
    private readonly IEventAggregator _eventAggregator;

    public BackgroundService(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
    }

    public async Task StartAsync()
    {
        await Task.Run(async () =>
        {
            try
            {
                while (!_cts.Token.IsCancellationRequested)
                {
                    await DoWorkAsync();
                    // 필요한 경우 이벤트 발생
                    await _eventAggregator.PublishAsync(new WorkCompletedEvent());
                    await Task.Delay(1000, _cts.Token);
                }
            }
            catch (OperationCanceledException)
            {
                // 정상적인 종료
            }
        }, _cts.Token);
    }

    public Task StopAsync()
    {
        _cts.Cancel();
        return Task.CompletedTask;
    }

    private async Task DoWorkAsync()
    {
        // 실제 작업 수행
    }
}
public partial class App : PrismApplication
{
    private IBackgroundService _backgroundService;

    protected override void OnInitialized()
    {
        base.OnInitialized();

        // DI 컨테이너에서 서비스 가져오기
        _backgroundService = Container.Resolve<IBackgroundService>();
        // 서비스 시작
        _backgroundService.StartAsync();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        // 서비스 종료
        _backgroundService?.StopAsync().Wait();
        base.OnExit(e);
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterSingleton<IBackgroundService, BackgroundService>();
    }
}

답글 남기기