ASP.NET Core 应用程序中 IHostedService 之间的同步

问题描述 投票:0回答:1

我有一个 ASP.NET Core 应用程序,其中有 2 个使用

IHostedService
实现的后台服务:

StartupService       // performs some action after app starts only once
TimerBasedService    // performs some action periodically 

它们之间同步的正确方法是什么,即

TimerBasedService
的操作应在
StartupService
的操作完成后首次执行?正在使用同步对象 像这里的锁定或手动重置事件正确吗?预先感谢

c# multithreading asp.net-core
1个回答
0
投票

您可以创建一个同步机制,例如布尔标志(通过使用

ManualResetEventSlim
),指示
StartupService
的操作是否已完成。

在 Startup 或 Program 类中,首先注册

StartupService
并确保它设置了指示其完成的标志。然后,注册
TimerBasedService
,确保它在执行操作之前检查此标志。

一个简单的演示:

public class StartupService : IHostedService
{
    private readonly ManualResetEventSlim _startupCompleted;

    public StartupService(ManualResetEventSlim startupCompleted)
    {
        _startupCompleted = startupCompleted;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        // Perform startup actions here
        _startupCompleted.Set(); // Signal that startup is completed
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

public class TimerBasedService : IHostedService, IDisposable
{
    private readonly ManualResetEventSlim _startupCompleted;
    private readonly Timer _timer;

    public TimerBasedService(ManualResetEventSlim startupCompleted)
    {
        _startupCompleted = startupCompleted;
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); 
    }

    private void DoWork(object state)
    {
        if (_startupCompleted.IsSet)
        {
            // do your stuff...
        }
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

程序.cs:

var startupCompleted = new ManualResetEventSlim(false);
builder.Services.AddSingleton(startupCompleted);
builder.Services.AddHostedService<StartupService>();
builder.Services.AddHostedService<TimerBasedService>();
© www.soinside.com 2019 - 2024. All rights reserved.