【问题标题】:Delaying a task in C# - db context disposed延迟 C# 中的任务 - 数据库上下文已处理
【发布时间】:2020-12-22 14:20:12
【问题描述】:

我需要在某个时间执行某些代码(在我的 ASP .NET Core 项目中)。

我知道延迟任务不是一个很好的解决方案,但这就是我所拥有的,我想知道如何让它发挥作用:

async Task MyMethod()
{
  // do something
  // Create a new thread that waits for the appropriate time
      TimeSpan time = dbAppointment.ScheduledOn - TimeSpan.FromMinutes(5.0) - DateTime.UtcNow;
      _ = Task.Delay(time).ContinueWith(async x => await 
          notificationManager.CreateReminder());
  // continue doing something
}

当我尝试运行代码时,它会在正确的时间进入应该执行的方法:

public async Task CreateReminder() {}

但是当它尝试使用我使用 DI 注入到 NotificationManager 构造函数中的 dbContext 时失败,说明它已被处置。

这是依赖的“流程”:

public class MyClass
{
  private readonly MyContext dbContext;
  private readonly INotificationManager notificationManager;
  public MyClass(MyContext context, INotificationManager nm) 
  { 
    dbContext = context;
    notificationManager = nm;
  }

  public async Task MyMethod() // the method shown in the snippet above
  { 
    // method does something using the dbContext

    _ = Task.Delay(time).ContinueWith(async x => await 
          notificationManager.CreateReminder());
  }
}

public class NotificationManager: INotificationManager
{
  private readonly MyContext dbContext;
  public NotificationManager(MyContext context) { dbContext = context;}
  public async Task CreateReminder() { // this method uses the dbContext}
}

startup.cs 中的 DI 设置:

services.AddDbContext<MyContext>(); 
services.AddScoped<INotificationManager, NotificationManager>();

【问题讨论】:

  • 至于“为什么”:stackoverflow.com/q/40844151/11683
  • 只是好奇:为什么不await Task.Delay(time); await notificationManager.CreateReminder();
  • @Fildor 在 startup.cs 中:services.AddDbContext&lt;MyContext&gt;(); services.AddScoped&lt;INotificationManager, NotificationManager&gt;();
  • 我将其添加到您的问题中。希望你不要介意。
  • @Arman 我最终使用了 Hangfire 库,它使用起来非常简单,可以满足我的一切需求!

标签: c# asp.net-core .net-core dependency-injection garbage-collection


【解决方案1】:

选项

在这两种情况下,您都需要在作业类中注入 DatabaseContext,否则您将收到 ObjectDisposedException。

当您需要横向扩展至多台机器时,您需要一个带有状态存储的作业服务器,例如 SQL Server、MSMQ、RabbitMQ、Redis...

Hangfire 示例

public class MyDelayJob
{
   private readonly MyContext dbContext;
   private readonly INotificationManager notificationManager;
   public MyDelayJob(MyContext context, INotificationManager nm)
   {
       dbContext= context;
       notificationManager = nm;
   }

   public async Task Run(/*parameters*/)
   {
      await notificationManager.CreateReminder()
   }
}

/*Shedule code in MyMethod
    IBackgroundJobClient can be injected
    you need to register MyDelayJob with your IOC container.
 */

backgroundJobClient.Schedule<MyDelayJob>(j => j.Run(), TimeSpan.FromSeconds(60))

查看IBackgroundJobClient的文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多