# Custom TaskScheduler: Limited concurrency level [closed]

I'm interested in some feedback for a custom TaskScheduler implementation I wrote today for use on a game server - I wanted to be able to have a single-threaded scheduler for tasks since the game is relatively lightweight and its logic doesn't need to be multi-threaded. However, I wanted to handle networking/IO concurrently to avoid blocking the main thread running game logic, and still wanted the ability to easily schedule tasks onto it, jumping back and forth between executors (e.g. game server receives a request, does some logic, then requires something from a database, makes a call on some other thread pool, then executes a callback on the original thread again). Anyway, that's probably too much about why I wanted to do this; Here's how I attempted it:

public class CustomTaskScheduler : TaskScheduler
{

{
}

{
}

{

{
{
try
{
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
}
}, null);
}
else
{
}
}

{
return false;
}


It isn't that complicated, but there are a few things I was wondering about - It is based off of the sample code here, but elects to use a ConcurrentQueue instead of locking on a LinkedList. From what I can see, this causes no issues. Then, I did an interlocked increment on the number of threads running to make sure it was not exceeding the limit, decrementing it immediately if another thread could not be run. This, too, I think is safe and correct, but it still makes me uncomfortable, and I was wondering if there was a more elegant solution to this. I found the Interlocked.CompareExchange function, but what i'm more looking for is being able to compare if something is less than something else.
Finally, I have tried doing some research on TryExecuteTaskInline, and it seems that this allows you to run a task directly from the thread creating the task, which seems like what I don't want. For now I've set it to always return false, but i'm not sure if this is what i'm supposed to do, or if i'm misunderstanding what it is actually doing.
• Feel free to edit the question (as long as it has no answers) with new version. The problem indeed is that the increment-check-decrement is not atomic as a whole (and the reason it is done under lock in the example - QueueTask). – user52292 Sep 28 '18 at 18:42
• P.S.: If you really want to have single-threaded scheduler then you can use Interlocked.CompareExchange to achieve that (which, together with supposedly lock-free queue, could actually be very good solution, but be careful, still won't be trivial). – user52292 Sep 28 '18 at 18:54
• Take a look at ConcurrentExclusiveSchedulerPair or more specifically ConcurrentExclusiveSchedulerPair.ConcurrentScheduler which is the built-in way of doing it. – Johnbot Aug 1 '19 at 9:22