[英]Is there a way to have a thread running in the background in a C# ASP.Net Web Forms web application regardless of what page is loaded?
I'm working on a C# ASP.Net Web Forms application.我正在研究 C# ASP.Net Web Forms 应用程序。 I need to call an API three times a day and update tables with the data.
我需要每天三次调用 API 并使用数据更新表。 Is there a way to have a thread running in the background doing this regardless of what page is loaded?
有没有办法让一个线程在后台运行,而不管加载了什么页面?
A simple Task
could do this for you:一个简单的
Task
可以为您做到这一点:
void MyFabulousApiCall()
{
// API magic happens here
}
// Let the task perform your api-calls while your application is running
bool appIsRunning = true;
var task = Task.Run(() =>
{
int callsPerDay = 3;
var now = DateTime.Now;
var endOfDay = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
var remainingHours = (endOfDay - now).TotalHours;
int delayPerCallInMs = (int)(remainingHours / callsPerDay * 60 * 60 * 1000);
while (appIsRunning)
{
MyFabulousApiCall();
Thread.Sleep(delayPerCallInMs);
}
});
This example would perform a given action X times a day, beginning with the starting time of your application.此示例将每天执行 X 次给定操作,从应用程序的开始时间开始。 Of course you'd still cover restarting the task when something went wrong or cancelling the task if you don't need it anymore.
当然,您仍然可以在出现问题时重新启动任务或在不再需要时取消任务。
You could put it into your eg Startup.cs
class to make sure that the api-call gets executed right after the apps' start.您可以将其放入您的例如
Startup.cs
class 中,以确保在应用程序启动后立即执行 api 调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.