I'm creating a Selenium bot as a WPF application. I'm using Tasks to create bots and then tasks to perform things on bot.
foreach (string account in accounts)
{
count++;
_ = Task.Run(async () =>
{
Bot bot = new Bot();
//here is long code for what should bot do ASYNC
//example
await bot.Connect();
await bot.SendTokens();
await bot.SayHi();
});
await Task.Delay(600);
}
I have array of accounts and I loop through them.
Let's say accounts.Length = 10
=> I want to create 10 tasks that will 'have their own life' and run async inside of them.
My problem is that Tasks wait for each other. Loop will create 10 tasks gradually (because of Task.Delay(600)
) => Bot will be created and start bot.Connect();
Lets say it takes always same amount of time to complete Connect()
.
Logically first Task should be completed 600ms faster than second Task. Problem is that program waits until all Connect()
are completed. Then it starts gradually all SendTokens()
then complete them, but first task won't start SayHi()
until SendTokens()
of last bot in list is completed.
Why is that happening, I don't understand that. I tried setting
ThreadPool.SetMaxThreads(500, 500);
but that does nothing for me.
Here is example of live debug output, starts LoadOptions()
gradually many times, but first LoadOptions()
should be already completed and next method should be already started but it is waiting for all LoadOptions
to end. I don't use in code Task.WaitAll()
.
Can anyone help me fix this issue and tell me what was wrong? I want to learn and know in future. Thank you very much and have a nice day.