0

I have an unending async in a kestrel server. Is there anything wrong with this:

   public static async void infiniteAsync()
            {
                bool keepgoing = true;
    
                // otherwise meaningless await to overcome 
                // "this 'async' method lacks await operators... will run synchronously"
                await Task.Delay(100); 
    
                do
                {
                    // streaming task that will never end;
                }
                while (keepgoing);
            }
}

invoked by kestrel server

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseWebSockets();
            infiniteAsync();
}
patrick
  • 16,091
  • 29
  • 100
  • 164
  • no its will run without problem and if you want you can use Task type instance of void to more control and if you want you can use [CancellationToken](https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken) for control method life time – amirhosein adlfar Feb 25 '22 at 17:07
  • 2
    It seems that you can be interested in [background tasks with hosted services in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio) – Guru Stron Feb 25 '22 at 17:17
  • Never use `async void`. Also, don’t abuse await Task.Delay just to get a warning away. If you want to run sync code asynchronously use Task.Run. Aside from that if you want to have a background task then do as Guru Strom linked. – ckuri Feb 25 '22 at 19:30
  • await Task.FromResult(1) is "better" to get rid of the warning – Charles Feb 25 '22 at 19:35
  • Related: [Suppress warning CS1998: This async method lacks 'await'](https://stackoverflow.com/questions/13243975/suppress-warning-cs1998-this-async-method-lacks-await) – Theodor Zoulias Feb 25 '22 at 22:31
  • @Charles "await Task.FromResult(1) is "better" to get rid of the warning" - no the best is to use `Task.Run` to have it actually running on an thread-pool-thread from the start, or use `await Task.Yield()` – Ackdari Feb 28 '22 at 08:42

1 Answers1

0

If you call this code inside the Startup class the operations will be canceled when the server is shutdown (Operation Cancelled Exception). The recommended approach would be to use a Background task.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio

b2f
  • 196
  • 2
  • 10