private static void WriteOperationLog(MultiThreading mt)
        {
            StreamWriter sw = File.AppendText(FILENAME);

            sw.WriteLine(DateTime.Now.ToString("F"));
            sw.WriteLine("Multithreading:\t" + mt);
            sw.Close();
        }
        public void AddToListWithOutThreading()
        {
            List <EmployeeModel> empList        = AddingDataToList();
            MultiThreading       multiThreading = new MultiThreading();
            Stopwatch            stopwatch      = new Stopwatch();

            stopwatch.Start();
            multiThreading.AddEmployeeToPayRoll(empList);
            stopwatch.Stop();
            Console.WriteLine("Time taken to add to db without threads is :{0} ms", stopwatch.ElapsedMilliseconds);
        }
Example #3
0
        public void givenDetails_WhenAddedToList_WithThreading()
        {
            MultiThreading       ops             = new MultiThreading();
            List <EmployeeModel> Models          = AddingDataToList();
            DateTime             startTimeThread = DateTime.Now;

            ops.AddEmployeePayrollwithThread(Models);
            DateTime stopTimethread = DateTime.Now;

            Console.WriteLine("Duration with thread :" + (stopTimethread - startTimeThread));
        }
Example #4
0
    public static void generateJsonGameTree(GameState <T> state, string outName, int playerID)
    {
        state.generateFuture();

        for (int max = 0; max < SystemInfo.processorCount / 2; max++)
        {
            MultiThreading.startNewThread((int)(ThreadingConstants.MB_IN_BYTES * 40));
        }

        foreach (GameState <T> child in state.childGameStates)
        {
            GameState <T> c = child;
            MultiThreading.loadBalanceTask(() => {
                generate(c);
                Debug.Log("GENERATED:" + c);
            });
        }

        string loc = Application.persistentDataPath;

        int thread = 0;

        thread = MultiThreading.loadBalanceTask(() => {
            while (MultiThreading.threadsIdle(thread))
            {
                Thread.Sleep(1000);
            }

            Debug.Log("AI STARTED");
            foreach (GameState <T> child in state.childGameStates)
            {
                GameState <T> c = child;
                MultiThreading.loadBalanceTask(() => GameTreeAI <T> .generatePercentHeuristic(c));
            }

            thread = MultiThreading.loadBalanceTask(() => {
                while (MultiThreading.threadsIdle(thread))
                {
                    Thread.Sleep(1000);
                }

                Debug.Log("WRITING JSON");
                using (StreamWriter file = File.CreateText(loc + "/" + outName + ".json"))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(file, state);
                }

                Debug.Log("DONE");
                MultiThreading.stopAll();
            });
        });
    }
        public void AddToDataBaseWithThreading()
        {
            List <EmployeeModel> empList  = AddingDataToList();
            bool           expected       = true;
            MultiThreading multiThreading = new MultiThreading();
            Stopwatch      stopwatch      = new Stopwatch();

            stopwatch.Start();
            bool actual = multiThreading.AddMultipleEmployeeToDataBaseWithThreading(empList);

            stopwatch.Stop();
            Console.WriteLine("Time taken to add to db without threads is :{0} ms", stopwatch.ElapsedMilliseconds);
            Assert.AreEqual(expected, actual);
        }
Example #6
0
        public void givenDetails_WhenUpdatedToListWithThreading_ShouldUpdateTheList()
        {
            List <EmployeeModel> models = updateList();
            bool           expected     = true;
            MultiThreading ops          = new MultiThreading();
            Stopwatch      stopwatch    = new Stopwatch();

            stopwatch.Start();
            bool actual = ops.UpdateMultipleEmployeeToDBWithThreading(models);

            stopwatch.Stop();
            Console.WriteLine("Time taken to add to db without threads is :{0} ms", stopwatch.ElapsedMilliseconds);
            Assert.AreEqual(expected, actual);
        }
Example #7
0
        public void givendetails_WhenAddedWithThreading_ShouldReturnEqual()
        {
            List <EmployeeModel> Models = AddingDataToList();
            MultiThreading       ops    = new MultiThreading();
            bool      expected          = true;
            Stopwatch stopwatch         = new Stopwatch();

            stopwatch.Start();
            bool actual = ops.AddEmployeesToDBWithThread(Models);

            stopwatch.Stop();
            Console.WriteLine("Time taken to add without threads is :{0} ms", stopwatch.ElapsedMilliseconds);
            Assert.AreEqual(expected, actual);
        }
Example #8
0
        public void givendetails_WhenAddedWithoutThreading_ShouldReturnEqual()
        {
            List <EmployeeModel> listModel = AddingDataToList();
            bool           expected        = true;
            MultiThreading ops             = new MultiThreading();
            Stopwatch      stopwatch       = new Stopwatch();//to measure elasped time

            stopwatch.Start();
            bool actual = ops.AddMultipleElementToDB(listModel);

            stopwatch.Stop();
            Console.WriteLine("Time taken to add without thread is :{0} ms", stopwatch.ElapsedMilliseconds);//in milliseconds
            Assert.AreEqual(expected, actual);
        }
Example #9
0
        public int CheckAllProxies()
        {
            _goodProxies = new List <string>();

            var mt = new MultiThreading(_proxies.Count);

            mt.RunForEach(_proxies, CheckProxy);

            while (mt.Working)
            {
                Thread.Sleep(1);
            }
            return(_goodProxies.Count);
        }
Example #10
0
        private static void Main(string[] args)
        {
            var path = args[0];
            ISupportedFileTypes            supportedFileTypes            = new SupportedFileTypes();
            IMultiThreading                multiThreading                = new MultiThreading();
            IFileListFromPath              fileListFromPath              = new FileListFromPath(multiThreading);
            ISupportedMediaFileTypesFilter supportedMediaFileTypesFilter = new SupportedMediaFileTypesFilter(supportedFileTypes);
            IPathToScan                pathToScan                = new PathToScan(path);
            IMediaFiles                mediaFiles                = new MediaFiles(supportedMediaFileTypesFilter, fileListFromPath, pathToScan);
            IWritePlayList             writePlayList             = new WritePlayList(mediaFiles, pathToScan);
            IExecutePlayListGeneration executePlayListGeneration = new ExecutePlayListGeneration(writePlayList);

            executePlayListGeneration.Run();
            Console.WriteLine("done");
            Console.ReadLine();
        }
Example #11
0
        public static IEnumerable <ISiteEndpoint> TestAvailability(this IEnumerable <ISiteEndpoint> endpoints)
        {
            List <ISiteEndpoint> endpointList = new List <ISiteEndpoint>();
            List <Task>          epTaskList   = new List <Task>();

            foreach (ISiteEndpoint value in endpoints)
            {
                Task task = new Task(new Action(delegate
                {
                    ISiteEndpoint endpoint = value as ISiteEndpoint;

                    Stopwatch watcher = new Stopwatch();

                    SiteEndpoint endpointBlock = new SiteEndpoint();
                    watcher.Start();
                    bool isAvailable = WebOperations
                                       .CheckUriAvailability(endpoint.EndpointUrl, endpoint.Port, ref endpointBlock);
                    watcher.Stop();

                    if (endpointBlock != null)
                    {
                        endpoint.DestinationServer         = endpointBlock.DestinationServer;
                        endpoint.DestinationAddress        = endpointBlock.DestinationAddress;
                        endpoint.DestinationAddressType    = endpointBlock.DestinationAddressType;
                        endpoint.HostInformation           = endpointBlock.HostInformation;
                        endpoint.HttpProtocol              = endpointBlock.HttpProtocol;
                        endpoint.IsAvailable               = isAvailable;
                        endpoint.ServerResponse            = endpointBlock.ServerResponse;
                        endpoint.ServerResponseDescription = endpointBlock.ServerResponseDescription;
                        endpoint.ResponseTime              = endpointBlock.ResponseTime;

                        endpointList.Add(endpoint);
                    }

                    watcher.Reset();

                    if (MultiThreading.ActiveTaskCounter > 0)
                    {
                        MultiThreading.ActiveTaskCounter--;
                    }
                }));
                epTaskList.Add(task);
            }
            MultiThreading.Run(epTaskList);
            return(endpointList.AsEnumerable());
        }
    void loadGameTree(string loc)
    {
        MultiThreading.startNewThread((int)((SystemInfo.systemMemorySize * ThreadingConstants.MB_IN_BYTES) / 8));

        MultiThreading.loadBalanceTask(() => {
            using (StreamReader r = new StreamReader(loc))
            {
                string json = r.ReadToEnd();
                totalTree   = JsonConvert.DeserializeObject <GameState <T> >(json);
                currentTree = totalTree;
            }

            currentGame = new GameState <T>(totalTree.players.Length);
            Debug.Log("Loaded tree with " + allPossibleNum(totalTree) + " possibilities.");
            MultiThreading.stopAll();
        });
    }
Example #13
0
        private string ArchiveFolders()
        {
            var multiThreadingHelper = new MultiThreading();
            var filePath             = new FileListFromPath(multiThreadingHelper);
            var files = filePath.ValueFor(_initialDirectory, new FileListFromPathFilter());

            var counter = 0;

            foreach (var path in files)
            {
                var fileName = Path.GetFileName(path);
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    continue;
                }

                var createTime       = File.GetCreationTime(path);
                var directory        = path.Replace(fileName, string.Empty);
                var archiveTime      = $@"{createTime.Year}\{createTime.Month.ToString().PadLeft(2, '0')}";
                var archiveDirectory = $@"{directory}\{archiveTime}";
                var archiveFilename  = $@"{archiveDirectory}\{fileName}";
                //debug
                if (path.Contains(archiveTime))
                {
                    continue;
                }

                if (!Directory.Exists(archiveDirectory))
                {
                    Directory.CreateDirectory(archiveDirectory);
                }

                File.Move(path, archiveFilename);
                counter++;
            }

            var pluralHelper = counter != 1
                ? "files were"
                : "file was";

            return(counter != 0
                ? $"{counter} {pluralHelper} archived."
                : "Nothing has changed.");
        }
        public static IEnumerable <ISiteConnectionString> TestAvaiilabilty(this IEnumerable <ISiteConnectionString> connectionStrings)
        {
            List <ISiteConnectionString> connectionstringList = new List <ISiteConnectionString>();
            List <Task> csTaskList = new List <Task>();

            foreach (ISiteConnectionString value in connectionStrings)
            {
                Task task = new Task(new Action(delegate
                {
                    try
                    {
                        ISiteConnectionString connectionString = value;
                        Stopwatch watcher = new Stopwatch();

                        watcher.Start();
                        XConsole.WriteLine("CheckSQLDatabaseAccesibility:" + connectionString.RawConnectionString);
                        bool isAvailable = WebOperations.CheckSQLDatabaseAccesibility(connectionString?.RawConnectionString);
                        watcher.Stop();

                        connectionString.IsAvailable  = isAvailable;
                        connectionString.ResponseTime = watcher.ElapsedMilliseconds;
                        connectionstringList.Add(connectionString);

                        watcher.Reset();

                        if (MultiThreading.ActiveTaskCounter > 0)
                        {
                            MultiThreading.ActiveTaskCounter--;
                        }
                    }
                    catch (Exception ex)
                    {
                        XConsole.WriteLine(ex.ToString());
                        logManager.Write(ex.ToString());
                    }
                }));
                csTaskList.Add(task);
            }
            MultiThreading.Run(csTaskList);
            return(connectionstringList.AsEnumerable());
        }
Example #15
0
    public virtual void RunThread()
    {
        try {
            while (!stop)
            {
                if (tasks.Count != 0)
                {
                    (tasks.Peek().action)();
                    Task task = tasks.Dequeue();

                    if (task.debugTask)
                    {
                        DLog.Log("TASK " + task.taskID + " COMPLETED ON " + id, Color.blue);
                    }

                    MultiThreading.onCompletion(task);
                }
            }
        } catch (ThreadAbortException e) {
            DLog.Log(e.ToString(), Color.red);
        }
    }
Example #16
0
        public void Attack()
        {
            GetProxies();
            if (_proxies.Count != 0)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\nLoaded {0} proxies!\n", _proxies.Count);
                Console.ResetColor();
                _mt = new MultiThreading((_threads == -1) ? _proxies.Count : _threads);
                _mt.Run(AttackThread);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("All {0} threads started!", _mt.ThreadCount);
                Console.ResetColor();

                while (_mt.Working)
                {
                    if (_proxies.Count <= _criticalProxiesCount)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("CRITICAL PROXY COUNT! RESTART INITIALIZED!");
                        Console.ResetColor();
                        Stop();
                        break;
                    }
                }
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("ALL THREADS STOPPED!");
                Console.ResetColor();
                Console.ReadKey();
                Attack();
            }
            else
            {
                Console.WriteLine("No proxies!");
            }
        }
        public static void Run(int size, MultiThreading multiThreadingSetting, string filename)
        {
            FILENAME = filename + ".txt";

            // Zapis daty i godziny rozpoczęcia badania
            WriteOperationLog(multiThreadingSetting);

            // Tworzenie macierzy 3 typów
            mtA = new MyMatrix <MyType>(Randomizer <MyType> .GenerateMatrix(size));
            mtX = new MyMatrix <MyType>(Randomizer <MyType> .GenerateVector(size));

            Serializer.PackMatrix(mtA, filename);
            Serializer.PackVector(mtX, filename);

            dA = new MyMatrix <double>(size, size);
            dX = new MyMatrix <double>(size, 1);

            fA = new MyMatrix <float>(size, size);
            fX = new MyMatrix <float>(size, 1);

            // Wypełnianie macierzy tymi samymi danymi
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    dA.Data[i][j] = (double)mtA.Data[i][j];
                    fA.Data[i][j] = (float)dA.Data[i][j];
                }

                dX.Data[i][0] = (double)mtX.Data[i][0];
                fX.Data[i][0] = (float)dX.Data[i][0];
            }



            // Definiowanie testów w threadach

            // Uruchamianie Gaussa w 6 wariantach na raz
            Thread[] tOnWithoutMyType = new Thread[6]
            {
                new Thread(() => GaussTestSpecific <float> .Run(fA, fX, Choice.NONE)),
                new Thread(() => GaussTestSpecific <float> .Run(fA, fX, Choice.PARTIAL)),
                new Thread(() => GaussTestSpecific <float> .Run(fA, fX, Choice.FULL)),

                new Thread(() => GaussTestSpecific <double> .Run(dA, dX, Choice.NONE)),
                new Thread(() => GaussTestSpecific <double> .Run(dA, dX, Choice.PARTIAL)),
                new Thread(() => GaussTestSpecific <double> .Run(dA, dX, Choice.FULL)),
            };

            // Uruchamianie Gaussa w 3 wariantach MyType na raz
            Thread tMyTypeNONE    = new Thread(() => GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.NONE));
            Thread tMyTypePARTIAL = new Thread(() => GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.PARTIAL));
            Thread tMyTypeFULL    = new Thread(() => GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.FULL));

            // Uruchamianie Gaussa w 9 wariantach po kolei
            Thread tOffWithMyType = new Thread(() =>
            {
                GaussTestSpecific <float> .Run(fA, fX, Choice.NONE);
                GaussTestSpecific <float> .Run(fA, fX, Choice.PARTIAL);
                GaussTestSpecific <float> .Run(fA, fX, Choice.FULL);

                GaussTestSpecific <double> .Run(dA, dX, Choice.NONE);
                GaussTestSpecific <double> .Run(dA, dX, Choice.PARTIAL);
                GaussTestSpecific <double> .Run(dA, dX, Choice.FULL);

                GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.NONE);
                GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.PARTIAL);
                GaussTestSpecific <MyType> .Run(mtA, mtX, Choice.FULL);
            });

            // Uruchamianie Gaussa w 6 wariantach po kolei
            Thread tOffWithoutMyType = new Thread(() =>
            {
                GaussTestSpecific <float> .Run(fA, fX, Choice.NONE);
                GaussTestSpecific <float> .Run(fA, fX, Choice.PARTIAL);
                GaussTestSpecific <float> .Run(fA, fX, Choice.FULL);

                GaussTestSpecific <double> .Run(dA, dX, Choice.NONE);
                GaussTestSpecific <double> .Run(dA, dX, Choice.PARTIAL);
                GaussTestSpecific <double> .Run(dA, dX, Choice.FULL);
            });

            // Nastawienie timera liczącego całkowity czas wszystkich funkcji
            Stopwatch stopWatch    = new Stopwatch();
            Thread    timerStopper = new Thread(() =>
            {
                while (true)
                {
                    if (!(anyThreadIsAlive(tOnWithoutMyType) || tMyTypeNONE.IsAlive || tMyTypePARTIAL.IsAlive || tMyTypeFULL.IsAlive || tMyTypeFULL.IsAlive || tOffWithMyType.IsAlive || tOffWithoutMyType.IsAlive))
                    {
                        stopWatch.Stop();
                        WriteWholeOperationTimer(stopWatch);
                        Console.Beep();
                        Console.Beep();
                        Console.Beep();
                        break;
                    }
                    Thread.Sleep(100);
                }
            });



            //Uruchamienie testów w threadach
            stopWatch.Start();

            switch (multiThreadingSetting)
            {
            case MultiThreading.ON_WITH_MY_TYPE:
                tOffWithoutMyType.Start();
                tMyTypeFULL.Start();
                tMyTypeNONE.Start();
                tMyTypePARTIAL.Start();
                break;

            case MultiThreading.ON_WITHOUT_MY_TYPE:
                foreach (Thread thread in tOnWithoutMyType)
                {
                    thread.Start();
                }
                break;

            case MultiThreading.OFF_WITH_MY_TYPE:
                tOffWithMyType.Start();
                break;

            case MultiThreading.OFF_WITHOUT_MY_TYPE:
                tOffWithoutMyType.Start();
                break;
            }

            timerStopper.Start();
        }
 public static void Run(int size, MultiThreading multiThreadingSetting)
 {
     Run(size, multiThreadingSetting, size.ToString() + "_" + multiThreadingSetting.ToString());
 }
Example #19
0
        static void Main()
        {
            Console.WriteLine("Starting Program...");
            Console.WriteLine("----------------------------------------");
            /************************************************Store Procedure Example*************************************************/
            //TODO: Connect to db so program can run
            StoredProcDemo spd = new StoredProcDemo();

            // run a simple stored procedure
            //!! spd.RunStoredProc();

            // run a stored procedure that takes a parameter
            //!! spd.RunStoredProcParams();
            /************************************************************************************************************************/


            /************************************************XML Deserialize using LINQ Example**************************************/
            XMLDeserializeLINQ xmlDeserialize = new XMLDeserializeLINQ();

            xmlDeserialize.startDeserialization();
            Console.WriteLine("****************************");
            /************************************************************************************************************************/


            /************************************************Loops Examples**********************************************************/
            Loops loop = new Loops();

            loop.forLoop();
            loop.whileLoop();
            loop.doWhileLoop();
            loop.nestedLoop();
            Console.WriteLine("****************************");
            /*************************************************************************************************************************/


            /************************************************Enum Example**********************************************************/
            Enums enumExample = new Enums();

            enumExample.displayEnumValues();
            Console.WriteLine("****************************");
            /*************************************************************************************************************************/


            /*************************************************Struct example**********************************************************/
            Structure structExample = new Structure();

            structExample.displayStructure();
            Console.WriteLine("****************************");
            /*************************************************************************************************************************/


            /*************************************************Array/Foreach example**********************************************************/
            ArrayAndForeach arrayExample = new ArrayAndForeach();

            arrayExample.displayArray();
            Console.WriteLine("****************************");
            /*************************************************************************************************************************/


            /*************************************************Array/Foreach example**********************************************************/
            MultiThreading multiThread = new MultiThreading();
            //multiThread.startSleepyThread();
            //multiThread.startAbortingThread();
            //Console.WriteLine("****************************");
            /*************************************************************************************************************************/


            /*************************************************Data Manipulation example**********************************************************/
            DataManipulation myData = new DataManipulation();
            var results             = myData.getData();

            foreach (var character in results)
            {
                Console.WriteLine("Name: {0}", character.name);
                Console.WriteLine("height: {0}", character.height);
                Console.WriteLine("Mass: {0}", character.mass);
                Console.WriteLine("Hair Color: {0}", character.hair_color);
                Console.WriteLine("Skin Color: {0}", character.skin_color);
                Console.WriteLine("Eye Color: {0}", character.eye_color);
                Console.WriteLine("Gender: {0}", character.gender);
                Console.WriteLine("Home World: {0}", character.homeworld);
                Console.WriteLine("*------*");
            }
            Console.WriteLine("****************************");
            /*************************************************************************************************************************/
        }