[英]EFCore - How to run simple query on a loop?
I'm working on a project where users can queue up actions to happen in the future.我正在做一个项目,用户可以在其中排队将来发生的动作。 Each future action is saved in the database.
每个未来的动作都保存在数据库中。 I'm trying to find a way to get all the actions that have already passed and act on them.
我正在尝试找到一种方法来获取所有已经通过的操作并对其进行操作。 Currently I'm doing this:
目前我正在这样做:
public class TaskingManager
{
private static readonly System.Timers.Timer RefreshEventsLoop = new(1000);
public void Initialize()
{
RefreshEventsLoop.Elapsed += RefreshEventsLoop_Elapsed;
RefreshEventsLoop.AutoReset = false;
RefreshEventsLoop.Start();
}
private void RefreshEventsLoop_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
RefreshEventsLoop.Enabled = false;
ProcessEventsQueue();
RefreshEventsLoop.Enabled = true;
}
private void ProcessEventsQueue()
{
var timeNow = DateTime.UtcNow;
var context = new GalaxyDbContext(_dbOptions);
var dbFunctions = new DatabaseFunctions(context);
var eventsToProcess = context.FutureEvents
.Where(futureEvent => futureEvent.TriggerTime <= timeNow)
.ToList();
if (eventsToProcess.Any())
{
context.FutureEvents.RemoveRange(eventsToProcess);
context.SaveChanges();
foreach (var pastEvent in eventsToProcess)
{
_messageMap[pastEvent.MessageType].Invoke(dbFunctions).Execute(pastEvent);
}
}
else
{
dbFunctions.CreateFutureScienceTask();
}
}
}
This seems to work ok.这似乎工作正常。 But the problem is that after the app has been running for a while, I can see the LINQ part is taking up a huge amount of memory: 524MB used
但问题是应用程序运行一段时间后,我可以看到 LINQ 部分占用了大量 memory: 524MB used
And if I leave it running for a few days then it's up in the gigs.如果我让它运行几天,那么它就会投入使用。
I'm guessing running this query every second is wasteful on resources.我猜每秒运行一次这个查询会浪费资源。 But I don't know of a better way to do this.
但我不知道有更好的方法来做到这一点。 Is there a way to continuously check the database for something like this?
有没有办法持续检查数据库中的此类内容?
The first thing i can see is that you are not disposing the databasecontextt afer you used it.我能看到的第一件事是你在使用它之后没有处理数据库上下文。 Read this for more info about entityframework context lifetime.
阅读本文以获取有关 entityframework 上下文生命周期的更多信息。
To properly dispose it use a using statement.要正确处理它,请使用 using 语句。
using (var context = new GalaxyDbContext(_dbOptions))
{
//your code that uses the context
}
Or with new using syntax:或者使用新的使用语法:
using (var context = new GalaxyDbContext(_dbOptions));
//your code that uses the context
Right know the problem could be that you create a context everytime you call the function and never dispose it and it still keeps references to the data etc..正确知道问题可能是您每次调用 function 时都创建了一个上下文并且从不处理它并且它仍然保留对数据等的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.