【发布时间】: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>();
【问题讨论】:
-
只是好奇:为什么不
await Task.Delay(time); await notificationManager.CreateReminder();? -
@Fildor 在 startup.cs 中:
services.AddDbContext<MyContext>(); services.AddScoped<INotificationManager, NotificationManager>(); -
我将其添加到您的问题中。希望你不要介意。
-
@Arman 我最终使用了 Hangfire 库,它使用起来非常简单,可以满足我的一切需求!
标签: c# asp.net-core .net-core dependency-injection garbage-collection