我想讓計(jì)時(shí)器在每60秒運(yùn)行一次method()的服務(wù)器上運(yùn)行現(xiàn)在我已經(jīng)完成了-使用以下代碼public class Alarm{ public Alarm(AppDbContext _db) { db = _db; } private static Timer aTimer; private AppDbContext db; public void StartTimerEvent() { // Create a timer and set a 60 second interval. aTimer = new Timer(); aTimer.Interval = 60000; // Hook up the Elapsed event for the timer. aTimer.Elapsed += (source, e) => CheckDBEvents(source, e); // Have the timer fire repeated events (true is the default) aTimer.AutoReset = true; // Start the timer aTimer.Enabled = true; } private void CheckDBEvents(Object source, ElapsedEventArgs e) { //get data from db with matching queries List<Grocery> DataList = db.Grocery.Where(G => G.basic).Select(G => new Grocery { Id = G.Id, Timeout = G.Timeout }).ToList(); }}method()是CheckDBEvents(),它的作用是訪問(wèn)dbcontext實(shí)例,并尋找一些數(shù)據(jù)保存到本地常量變量Called DataList中。問(wèn)題:每次我嘗試將上下文(Dbcontext)實(shí)例(在控制器或任何其他類(lèi)中)傳遞給CheckDBEvents()方法時(shí),都會(huì)處理該上下文-DbContext Disposed Exception。呼叫者,召集者var t = new Alarm(db);t.StartTimerEvent();我的輪胎:-使警報(bào)成為靜態(tài)類(lèi):現(xiàn)在,如果我能夠做到這一點(diǎn),那將是驚人的……但是無(wú)法在DbContext上進(jìn)行操作,因?yàn)槟鸁o(wú)法在靜態(tài)類(lèi)中調(diào)用DbContext上的實(shí)例,因此您必須將其傳遞給調(diào)用它的人,這會(huì)導(dǎo)致相同的問(wèn)題: db已處置且未通過(guò) public static void StartTimerEvent(AppDbContext db) { ..... // Hook up the Elapsed event for the timer. aTimer.Elapsed += (source, e) => CheckDBEvents(source, e, db //DbContext is Disposed here and //don't get passed' );而且常量類(lèi)和Dbcontext與我所閱讀的內(nèi)容相處得不太好。長(zhǎng)話短說(shuō) -我想保留的DbContext實(shí)例在另一個(gè)階級(jí),而不是控制器。沒(méi)有被處置。如果有人知道如何執(zhí)行此操作或有服務(wù)器端計(jì)時(shí)器的源代碼或類(lèi)似的內(nèi)容,請(qǐng)發(fā)表評(píng)論,我被困了2天
具有DbContext的服務(wù)器端計(jì)時(shí)器
繁星點(diǎn)點(diǎn)滴滴
2021-03-29 17:13:45