C # WinForms MultiThreading in Loop

Scenario

I have a background worker in my application that runs away and does a bunch of processing. I specifically used this implementation to maintain fluid in the user interface and prevent it from freezing. I want to keep the background worker, but ONLY 3 LARGE threads are posted inside this thread - forcing them to share processing (currently the worker thread is just outlines and processes each asset one at a time. However, I would like to speed up this process but using only a limited number of threads.

Question

Given the code below, how can I get a loop to select a thread that is free, and then essentially wait if it is not released before continuing.

CODE

        foreach (KeyValuePair<int, LiveAsset> kvp in laToHaganise)
        {

             Haganise h = new Haganise(kvp.Value,
                                      busDate,
                                      inputMktSet,
                                      outputMktSet, 
                                      prodType,
                                      noOfAssets, 
                                      bulkSaving);

             h.DoWork();

         }

Thoughts

, 3 , , Haganise - "h" .....

  Thread firstThread = new Thread(new ThreadStart(h.DoWork));
  Thread secondThread =new Thread(new ThreadStart(h.DoWork));
  Thread thirdThread = new Thread(new ThreadStart(h.DoWork));

.

+3
2

:

, :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        private static List<MyWorker> _Workers;

        static void Main(string[] args)
        {
            _Workers = new List<MyWorker>();

            for (int i = 0; i < 5; i++)
            {
                _Workers.Add(CreateDefaultWorker(i));
            }

            StartJobs(20000);
            Console.ReadKey();
        }

        private static void StartJobs(int runtime)
        {
            Random rand = new Random();
            DateTime startTime = DateTime.Now;

            while (DateTime.Now - startTime < TimeSpan.FromMilliseconds(runtime))
            {
                var freeWorker = GetFreeWorker();

                if (freeWorker != null)
                {
                    freeWorker.Worker.RunWorkerAsync(new Action(() => DoSomething(freeWorker.Index, rand.Next(500, 2000))));
                }
                else
                {
                    Console.WriteLine("No free worker available!");
                    Console.WriteLine("Waiting for free one...");
                    WaitForFreeOne();
                }
            }
        }

        private static MyWorker GetFreeWorker()
        {
            foreach (var worker in _Workers)
            {
                if (!worker.Worker.IsBusy)
                    return worker;
            }

            return null;
        }

        private static void WaitForFreeOne()
        {
            while (true)
            {
                foreach (var worker in _Workers)
                {
                    if (!worker.Worker.IsBusy)
                        return;
                }
                Thread.Sleep(1);
            }
        }

        private static MyWorker CreateDefaultWorker(int index)
        {
            var worker = new MyWorker(index);

            worker.Worker.DoWork += (sender, e) => ((Action)e.Argument).Invoke();
            worker.Worker.RunWorkerCompleted += (sender, e) => Console.WriteLine("Job finished in worker " + worker.Index);

            return worker;
        }

        static void DoSomething(int index, int timeout)
        {
            Console.WriteLine("Worker {1} starts to work for {0} ms", timeout, index);
            Thread.Sleep(timeout);
        }
    }

    public class MyWorker
    {
        public int Index { get; private set; }
        public BackgroundWorker Worker { get; private set; }

        public MyWorker(int index)
        {
            Index = index;
            Worker = new BackgroundWorker();
        }
    }
}
+1

Source: https://habr.com/ru/post/1740421/


All Articles