Reputation: 13
Have 1 main BackgroundWorker
and many of other. In time of starting other workers in main worker Task.Run
not running in expected time.
How to modify code to do all tasks(or threads) parallel?
static List<System.ComponentModel.BackgroundWorker> workers;
static System.ComponentModel.BackgroundWorker mainWorker;
static void Main(string[] args)
{
mainWorker = new System.ComponentModel.BackgroundWorker();
mainWorker.DoWork += MainWorker_DoWork;
mainWorker.RunWorkerAsync();
workers = new List<System.ComponentModel.BackgroundWorker>();
for (int i = 0; i < 50; i++)
{
workers.Add(new System.ComponentModel.BackgroundWorker());
workers[i].DoWork += FastAnalizWorker_DoWork;
workers[i].RunWorkerAsync(i);
System.Threading.Thread.Sleep(0);
}
}
static void MainWorker_DoWork(object sender,
System.ComponentModel.DoWorkEventArgs e)
{
while (true)
{
System.Threading.Thread.Sleep(1000);
Task.Run(() => ShowMessage("main"));
}
}
static void FastAnalizWorker_DoWork(object sender,
System.ComponentModel.DoWorkEventArgs e)
{
int index = (int)e.Argument;
System.Threading.Thread.Sleep(index * 1000);
ShowMessage(index.ToString());
}
static void ShowMessage(string message)
{
Console.WriteLine(string.Format("{0:mm ss}: {1}", DateTime.UtcNow, message));
}
Console result: Screenshot
Upvotes: 1
Views: 218
Reputation: 9221
Task.Run
have a big delay because you are causing thread pool starvation.
Both BackgroundWorker
and Task.Run
use the thread pool to do their job.
The thread pool starvation is caused because:
Thread.Sleep()
that blocks the current thread.BackgroundWorker's
than the thread pool sizeUpvotes: 2