I would like to have one specific thread, queue for Tasks and process tasks in that separate thread. The application would make Tasks based on users usage and queue them into task queue. Then the separate thread processes the tasks. It is vital to keep the thread alive and use it for processing queued tasks even if queue is empty.
I have tried several implementations of TaskScheduler
with BlockingCollection
and limit the concurrency to only one thread but it seems the Thread gets disposed when queue gets empty and the Task is processed by other thread.
Can you please at least refer me to some sources how to achieve this goal?
tl;dr Trying to limit one specific thread to process tasks which are dynamically added to the queue.
Edit1:
This is experimental web app that uses WCF and .NET framework 4.6. In the WCF library, I am trying to implement this behaviour with one thread processing tasks. This one thread must init prolog using external dll library and then do work with prolog. If other thread is used in process, library throws AccessViolationException
. I've done some research and this is most probably because of badly managed threading in that library. I had implementation where I had locks everywhere and it worked. I am now trying to reimplement and make it asynchronous so I don't block the main thread with locking.
I am not at my computer but I provide some code when I get home later today.
Your approach seems fine, so you probably just made some tiny stupid mistake.
It's actually pretty easy to make a simple custom
TaskScheduler
. For your case:It's pretty easy to modify this to give you full control on where the task scheduler is actually executing the task - in fact, I've adapted this from a previous task scheduler I've used which simply had the
RunOnCurrentThread
method public.For your case, where you always want to stick to just the one thread, the approach in
SingleThreadTaskScheduler
is probably better. Although this also has its merits: