Question:
Example from andreycha
pattern throttling
:
public async Task CheckServers()
{
var servers = new List<string>(10000) { ... };
const int ConcurrencyLevel = 100;
// запускаем первые 100 запросов
var tasks = servers.Take(ConcurrencyLevel).Select(GetVersion).ToList();
int nextIndex = ConcurrencyLevel;
while (tasks.Count > 0)
{
// дожидаемся завершения любого запроса
var completedTask = await Task.WhenAny(tasks);
// удаляем его из списка
tasks.Remove(completedTask);
// добавляем новый запрос, если таковые остались
if (nextIndex < servers.Count)
{
tasks.Add(GetVersion(servers[nextIndex++]));
}
string rfbVersion = await completedTask;
// работаем с версией
}
}
How to set TaskCreationOptions.LongRunning
tasks nicely in such an implementation? Is this even possible without using Task.Factory.StartNew
?
Answer:
Look. Let's split Task
'and other asynchronous functions into those that are processor-limited (that is, take up a fixed thread for a long time) and others.
For the first functions, TaskCreationOptions.LongRunning
makes sense, TaskCreationOptions.LongRunning
we don't want to block a thread from the thread pool for a long time. But such functions are usually provided in the form of synchronous functions that we run through Task.Run
. So you can, if you want, run it through Task.Factory.StartNew
.
For the rest of the asynchronous functions, there is no concept of "the thread in which the function runs", and most of the time the Task does not run anywhere , just waiting for the await
finish. For such functions, TaskCreationOptions.LongRunning
meaningless and difficult (if not impossible) to set. But in this case, this option is not needed.