Frage

Consider such code:

private static async Task ProcessSomethingAsync()
{
    while (true)
    {
        var message = await GetMessageAsync();
        await WriteAsync(message);
    }
}

Consider that GetMessageAsync and WriteAsync methods leverage asynchronous IO.

Imagine that I have several(from 2 to N) tasks like this, which live as long as application lives. To my opinion, since the code inside the loop is fully async, it is better not to use LongRunning option when I start such tasks, so that we will be able to leverage ThreadPool instead of creating thread per Task.

Is this correct or am I missing something?

War es hilfreich?

Lösung

it is better not to use LongRunning option when I start such tasks, so that we will be able to leverage ThreadPool instead of creating thread per Task.

When you're running async code, you should not specify LongRunning. If you do, then (as of today's implementation), the thread pool will start a new thread just to run the first part of your async code. As soon as your code yields at an await, that new thread will be disposed and the rest of the code will run on regular thread pool threads. So, LongRunning is usually counterproductive for async code.

I have a blog post on why StartNew is dangerous, and I (briefly) cover all of the TaskCreationOptions in that post:

AttachedToParent shouldn't be used in async tasks, so that's out. DenyChildAttach should always be used with async tasks (hint: if you didn't already know that, then StartNew isn't the tool you need). DenyChildAttach is passed by Task.Run. HideScheduler might be useful in some really obscure scheduling scenarios but in general should be avoided for async tasks. That only leaves LongRunning and PreferFairness, which are both optimization hints that should only be specified after application profiling. I often see LongRunning misused in particular. In the vast majority of situations, the threadpool will adjust to any long-running task in 0.5 seconds - without the LongRunning flag. Most likely, you don't really need it.

Andere Tipps

Yes, specifying LongRunning will potentially allow more threads to be created, because you are telling the scheduler that your task is going to hog a thread for a long time.

Async methods are exactly the opposite, they free up the thread to do other things without blocking.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top