Search code examples
asp.netwhile-loop

asp.net core run while(true) in separate process


I want to run a method which will always running like:

public async Task GetMessageUpdatesAsync()
{    
    while(true)
    {
        await GetUpdatesAsync();
    }
}

I want to run it in separate process. while my app continue run.

How ca I do it?

Update:

here is my method code

    public static async Task<string> GetUpdatesAsync()
    {
        string telegramToken = "Token";
        var botClient = new TelegramBotClient(telegramToken);
        int? updateId=null;
        while (true) // this will not break
        {
           var updates = await botClient.GetUpdatesAsync(updateId);
           foreach(var update in updates)
           {
               //do some thing
               updateId = update.Id + 1;
           }
        }
    }

I want previous method running while other website code working (like get information from database, update database information ...).

  • List item

Solution

  • An ASP.NET (web app) is not made to work for ever. Is only to work with a quick response to some request.

    You should create two projects to do this. There is no work or improvement added do it in the same project.

    If you are in windows, you can use a WinForm (desktop app) or Console App but the ideal to do this is create a service and running trough services.msc for ever.

    If you are in linux, I would do a Service as a daemon to work with systemctl in e.g., or a Console and run it with a cron task.

    Then if you wanna still do your stuff in an ASP.NET like a Web API you can call from that service to the API with HttpClient like RestSharp Client (you can get it from nuget), and then do the specific and finite task.