简体   繁体   English

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?

[英]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.

相关问题 ASP.NET C#Web窗体-如何在旧版应用程序中制作交互式CRUD页? - ASP.NET C# Web Forms - How to make an interactive CRUD page in a legacy application? 如何在同一个ASP.NET Web窗体应用程序中使用c#和vb.net代码? - How can I have c# and vb.net code behinds in the same ASP.NET Web Forms application? 在ASP.NET Web应用程序中连续运行线程 - continously running thread in asp.net web application 在ASP.NET Web应用程序中创建线程的正确方法 - right way to create thread in ASP.NET web application ASP.NET Web窗体中的后台进程 - Background processes in ASP.NET Web Forms 在 asp.net c# web 表单应用程序中自动化 html 元素按钮单击 - automate html element button click in asp.net c# web forms application 在asp.net web forms c#应用程序中保存时如何在文件名的末尾添加增量数字? - How to add incremental numbers to the end of a filename when saving in asp.net web forms c# application? 在移动版和桌面版ASP.NET C#Web应用程序(窗体)之间共享代码 - Sharing Code Between Mobile and desktop version of ASP.NET C# Web Application (Forms) 为什么在gridview上进行更新时不会在asp.net c#Web窗体应用程序中更新数据库? - Why update on gridview is not updating the database in my asp.net c# web forms application? 如何以所有形式在ASP.NET,C#Web应用程序中链接模块 - How to link a module in asp.net, C# web application in all forms
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM