Blazor Server - What is the best way to create/manage a background task/thread? #51358
-
Blazor server The specific use case I have is I have an ILoggerProvider and it has a background thread where it reads log message from a ConcurrentQueue and writes them to the log repository (Azure BLOB). So this thread gets spun up when the server starts and lives until the app is shut down. I figure this is a more general question though. For any case of having a background task/thread that is a worker daemon that has a long lifetime - what is the best way to do this? And a background daemon usually should have a lower priority so it is running when the processor is not that busy. At present I am using Task.Run() which means I've permanently grabbed a thread from the thread pool. I'm guessing that is not optimum. ??? - thanks - dave |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
It sounds like using a hosted service would suit your needs here. This would give you more control over the startup and shutdown as well. Although I'm not aware of anything that would allow you to change the priority of these background services out of the box. Article: Background tasks with hosted services in ASP.NET Core |
Beta Was this translation helpful? Give feedback.
-
messing with thread priorities could lead to unexpected result. usually this is the best way to do something like that:
|
Beta Was this translation helpful? Give feedback.
-
@DavidThielen, you're correct about the sleep issue. My intention was to suggest implementing it within a dedicated thread. To ensure everything operates within this thread, it's best to use the non-async functions provided by libraries. If you encounter a method that only offers an async variant, you can simply use .Wait or .Result to ensure its execution within that thread.
So it could look like this:
|
Beta Was this translation helpful? Give feedback.
-
small side note: In referencing the provided code, there's a potential issue where a consumer might be left waiting while a message remains in the queue.
PS: i dropped the List since the streams got buffers to do exactly that (and they can be set to any desired size) |
Beta Was this translation helpful? Give feedback.
@DavidThielen, you're correct about the sleep issue. My intention was to suggest implementing it within a dedicated thread.
To ensure everything operates within this thread, it's best to use the non-async functions provided by libraries. If you encounter a method that only offers an async variant, you can simply use .Wait or .Result to ensure its execution within that thread.
It's worth noting that we shouldn't use async merely because it's available. If you're certain that your task can be managed by a single thread, this approach is often more efficient. And you could set the Thread Priority if you want.
S…