相关疑难解决方法(0)

我在哪里可以记录ASP.NET Core应用程序的启动/停止/错误事件?

在旧的ASP.NET中,在Global.asax.cs类中,我会在应用程序启动时记录,停止并抛出未处理的异常:

  • Application_Start()
  • Application_End()
  • Application_Error()

我如何在ASP.NET Core中执行相同的操作?它有一个Startup类,但它用于配置.

我在哪里挂钩应用程序的开始/停止/错误事件?

c# asp.net asp.net-core

20
推荐指数
3
解决办法
8500
查看次数

Asp.Net核心长期运行/后台任务

以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗?或者我应该使用某种形式的Task.Run/ TaskFactory.StartNewwith TaskCreationOptions.LongRunning选项?

    public void Configure(IApplicationLifetime lifetime)
    {
        lifetime.ApplicationStarted.Register(() =>
        {
            // not awaiting the 'promise task' here
            var t = DoWorkAsync(lifetime.ApplicationStopping);

            lifetime.ApplicationStopped.Register(() =>
            {
                try
                {
                    // give extra time to complete before shutting down
                    t.Wait(TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    // ignore
                }
            });
        });
    }

    async Task DoWorkAsync(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            await // async method
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core

18
推荐指数
2
解决办法
1万
查看次数

.NET Core中运行时间短的任务

我刚刚发现了IHostedService.NET Core 2.1 BackgroundService类.我觉得这个想法太棒了.文档.

我发现的所有示例都用于长时间运行的任务(直到应用程序死亡).但我需要它很短的时间.这样做的正确方法是什么?

例如:
我想在应用程序启动后执行一些查询(大约需要10秒钟).并且只有在开发模式下.我不想延迟应用程序启动,所以IHostedService似乎很好的方法.我不能使用Task.Factory.StartNew,因为我需要依赖注入.

目前我这样做:

public class UpdateTranslatesBackgroundService: BackgroundService
{
    private readonly MyService _service;

    public UpdateTranslatesBackgroundService(MyService service)
    {
        //MService injects DbContext, IConfiguration, IMemoryCache, ...
        this._service = service;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await ...
    }
}
Run Code Online (Sandbox Code Playgroud)

启动:

public static IServiceProvider Build(IServiceCollection services, ...)
{
    //.....
    if (hostingEnvironment.IsDevelopment())
        services.AddSingleton<IHostedService, UpdateTranslatesBackgroundService>();
    //.....
}
Run Code Online (Sandbox Code Playgroud)

但这似乎有点矫枉过正.是吗?注册singleton(表示类在应用程序存在时存在).我不需要这个.只需创建类,运行方法,配置类.全部在后台任务.

c# .net-core asp.net-core

9
推荐指数
2
解决办法
6489
查看次数

标签 统计

asp.net-core ×3

c# ×3

.net-core ×2

asp.net ×1