C
C#β€’9mo ago
Jer

❔ Task tracking

Hi! I am writing an app that relies on HostedService(s). I've got a hosted services which has an HttpListener and whenever a new request comes in I use a Channel<T> to dispatch it to another HostedService that consumes this Channel. This all works great! Now, inside the RequestQueueWorker (the consumer of the Channel). I use Task.Run() and add the Task proxy into a list. So that in case of a graceful application shutdown I can use the StopAsync method of the HostedService to await Task.WhenAll(_runningTasks) to ensure that those tasks are indeed completed. However, ideally I'd want to clean up this list every once in a while and get rid of all tasks that are completed so that this list stays small. Throughout the lifetime of the app there could be thousands if not more Task's inside of this list. Is the clean up even needed from the get go? Is it overkill? Should I even care optimizing this part considering it's only on shutdown anyway? Thanks in advance! I hope I provided enough information, if not feel free to ask for more details! (Please tag me if you reply, so I get a notitication. Thanks πŸ™‚ )
7 Replies
David_F
David_Fβ€’9mo ago
@Jer maybe you can use .ContinueWith(...) method that accepts TaskContinuationOptions enum for each task to remove itself on completion from your collection of tasks @Jer you should avoid ever growing collections in any case. Cleaning only on shutdown is not enough
Jer
Jerβ€’9mo ago
Thanks! This would mean I’d have to lock on the List though. Right? Otherwise when I iterate it on shutdown the collection might be modified by the continuation during iteration of Task.WhenAll() (lock only just before calling Task.WhenAll()) to ensure exclusive access from the shutdown sequence)
David_F
David_Fβ€’9mo ago
@Jer maybe you can use ConcurrentBag<T> instead of List<T> to avoid locking by yourself. Another alternative is SynchronizedCollection<T> if you need index access to the list. Maybe ConcurrentBag<T> is enough for your use case
Jer
Jerβ€’9mo ago
Yeah that should be sufficient, although it might slow down the performance overall due it locking whenever any task finishes whereas with the manual lock it’s only on shutdown a single lock op until Task.WhenAll finishes (assuming the ConcurrentBag<T> locks on add/remove)
David_F
David_Fβ€’9mo ago
@Jer also remember to propagate or request from DI the cancellationToken that fires when shutdown is requested in every logic the tasks do because cancellation should be cooperative. ASP .NET Core by default gives a couple of seconds to allow gracefull shutdown and after these seconds pass, the process exits anyway not waiting for your background work
Jer
Jerβ€’9mo ago
I’ve increased the shutdown timeout Yeah I’m passing down the CT everywhere. I just want to do the most I can to process anything that was sent while the HttpListener was still processing even though the application was already gracefully being shut down Thanks for your help! @David_F
Accord
Accordβ€’9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
❔ Source Generators stopping Hot Reload in VS 2022Got a source generator (I didn't write it, someone I'm working with did tho) and it works in VS withβœ… CalcBinding "object not set to value" errorI'm using CalcBinding to bind some properties with `{CalcBinding:Binding 'SelectedValue == Defs:LogI❔ How to censor a bad word in capital letters without changing original letters case?I'm trying to loop through a list of bad words to filter them out, but when their case is different Delegate caching. Is it safe to use or some dirty hack to avoid? (code below)Here's some delegate caching into struct... ```cs using System; public class InstanceHandler<T> whβœ… Using SQLite with C#The next project of the C# Academy is creating a habit tracker. I'm a little confused on the SQLite βœ… public static async Task Main instead of public static void Main for dsharpplus setup?In tutorials I see that they use void, and they call an async method using GetAwaiter().GetResult().βœ… βœ… C# Academy Calculator Project Challenge -- Counting Times UsedCalculator.mekasu0124/Program.cs - https://pastebin.com/Wvz9eHUM ClassLibrary/CalculatorLibrary.cs -βœ… C# Academy Math Game Issues```cs public void StartDivGame(string username, DateTime date, int totalQuestions, string difficulty❔ Execute / Run local project `.csproj` NuGet packageI have a `package` installed from `NuGet` : https://github.com/killwort/dotnet-bump, and supposedly βœ… Blazor vs Razor PagesHello lovers of C#, I have a passion project that is basically a recipe manager. At the moment i'm