void BattleWork(object threadParams)
    {
        ThreadParams param = threadParams as ThreadParams;

        try
        {
            foreach (Battleground battleground in terrainManager.battlegrounds)
            {
                for (int i = param.startIndex; i <= param.endIndex; i++)
                {
                    foreach (Creature creatureB in population)
                    {
                        if (population[i] != creatureB)
                        {
                            BattleStats stats = BattleSimulation.Battle(population[i], creatureB, battleground);
                            stats.winner.fitnessValue++;
                            battles++;
                            requiresUIUpdate = true;
                        }
                    }
                }
            }
        }
        finally
        {
            param.currentHandle.Set();
        }
    }
Example #2
0
        public void ProcessSocketConnection(object threadState)
        {
            ThreadParams state = (ThreadParams)threadState;

            Console.WriteLine($"<SocketProcess>Thread {state.ThreadIndex} is processing connection"); //{state.ClientSocket.RemoteEndPoint}

            // This should be an extra method. In general this code should be more modular!
            byte[] recievBuffer = new byte[StorageSize];
            if (state.ClientSocket.Poll(DataTimeReadout, SelectMode.SelectRead))
            {
                state.ClientSocket.Receive(recievBuffer);
            }
            else
            {
                Console.WriteLine("<SocketProcess>Got no data, aborting");
                Cleanup();
            }
            // Do your data Processing in this Method.
            DoWork(recievBuffer, state.ClientSocket);
            Cleanup();
            // This is a local Function introduced in c#7
            void Cleanup()
            {
                Console.WriteLine("<SocketProcess>Doing clean up tasks");
                state.ClientSocket.Shutdown(SocketShutdown.Both);
                state.ClientSocket.Close();
                state.ClientSocket.Dispose();

                recievBuffer = new byte[StorageSize];

                state.ThreadHandle.Set();
            }
        }
    void CalculatePopulationFitnessThreaded()
    {
        ResetFitnessValue();
        battles = 0;

        if (populationSize / threadCount < threadCount)
        {
            threadCount = 2;
        }

        int threadSplit = populationSize / threadCount;

        ManualResetEvent[] handles = new ManualResetEvent[threadCount];

        for (int i = 0, j = 0; i < populationSize; i += threadSplit, j++)
        {
            handles[j] = new ManualResetEvent(false);
            ThreadParams threadParams = new ThreadParams(i * threadSplit, Mathf.Min(populationSize - 1, i * threadSplit + threadSplit - 1));
            threadParams.currentHandle = handles[j];
            ThreadPool.QueueUserWorkItem(BattleWork, threadParams);
        }

        WaitHandle.WaitAll(handles);

        //Sort highest fitness value to lowest
        population.Sort((creatureA, creatureB) => creatureB.fitnessValue.CompareTo(creatureA.fitnessValue));

        totalFitness = battles;
    }
Example #4
0
        static void Main()
        {
            var taskList = new Task[NUMBER_THREADs];

            Console.WriteLine("Main on thread = {0}", Thread.CurrentThread.ManagedThreadId);
            System.Diagnostics.Debug.WriteLine("Main on thread = {0}", Thread.CurrentThread.ManagedThreadId);

            ManualResetEvent[] doneThreads = new ManualResetEvent[NUMBER_THREADs];
            ManualResetEvent syncStartThreads = new ManualResetEvent(false);

            for (int i = 0; i < NUMBER_THREADs; i++)
            {
                doneThreads[i] = new ManualResetEvent(false);
                ThreadParams threadParams = new ThreadParams() { startEvent = syncStartThreads, finishedEvent = doneThreads[i] };
                var thr = new Thread(new ParameterizedThreadStart(ThreadRun));
                thr.Start(threadParams);
            }

            syncStartThreads.Set();

            WaitHandle.WaitAll(doneThreads);
            Console.WriteLine("Finished processing {0} threads", NUMBER_THREADs);
            System.Diagnostics.Debug.WriteLine("Finished processing {0} threads", NUMBER_THREADs);
            Console.ReadLine();


           
        }
Example #5
0
        private static void readFileThreadPool(object tParams)
        {
            //read the custom thread parameter object
            ThreadParams tParamsInner   = tParams as ThreadParams;
            string       sourceFileName = @tParamsInner.sourceFileName;

            StringBuilder contents = new StringBuilder();
            string        nextLine;
            int           lineCounter = 1;

            var sw = Stopwatch.StartNew(); // time the operation

            using (var stream = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
            {
                using (var reader = new StreamReader(sourceFileName))
                {
                    while ((nextLine = reader.ReadLine()) != null)
                    {
                        contents.AppendFormat("{0}. ", lineCounter);
                        contents.Append(nextLine);
                        contents.AppendLine();
                        lineCounter++;

                        textMethod.Append(nextLine);
                        textMethod.AppendLine();
                    }
                }
            }

            textTime.Text = Convert.ToString(sw.Elapsed);
            textMethod.AppendLine("Ending Tread Pool I/O...");
        }
Example #6
0
        public void InitializeSocketProcessing()
        {
            waitHandles = new WaitHandle[MaxThreads];
            for (int i = 0; i < MaxThreads; ++i)
            {
                waitHandles[i] = new AutoResetEvent(true);
            }

            listener = new Socket(SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress, Port));
            listener.Listen(25);

            while (true)
            {
                Console.WriteLine($"{prefix}Waiting for a TCP connection");
                Socket sock = listener.Accept();

                Console.WriteLine($"{prefix}Got a connection");
                Console.WriteLine($"{prefix}Waiting for idle thread");
                int index = WaitHandle.WaitAny(waitHandles);

                Console.WriteLine($"{prefix}Starting new thread to process client");

                ThreadParams context = new ThreadParams()
                {
                    ThreadHandle = (AutoResetEvent)waitHandles[index],
                    ClientSocket = sock,
                    ThreadIndex  = index
                };
                ThreadPool.QueueUserWorkItem(ProcessSocketConnection, context);
            }
        }
Example #7
0
        static void Thread(object arg)
        {
            ThreadParams threadParams = (ThreadParams)arg;

            while (!stop_)
            {
                try
                {
                    // Request the server
                    if (threadParams.level2)
                    {
                        // Request for the level2 history
                        var result = threadParams.client.QueryQuoteHistoryTicks(threadParams.timestamp, threadParams.count, threadParams.symbol, true);
                    }

                    if (threadParams.ticks)
                    {
                        // Request for the ticks history
                        var result = threadParams.client.QueryQuoteHistoryTicks(threadParams.timestamp, threadParams.count, threadParams.symbol, false);
                    }

                    if (threadParams.bars)
                    {
                        // Request for the bars history
                        var result = threadParams.client.QueryQuoteHistoryBars(threadParams.timestamp, threadParams.count, threadParams.symbol, threadParams.periodicity, threadParams.priceType);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Error : " + exception.Message);
                }
            }
        }
Example #8
0
 /// <summary>
 /// Write record for squad i in XML file
 /// </summary>
 /// <param name="id">Squad ID. Defferent with IndexId which starts with zero</param>
 /// <param name="record">String to write into XML element</param>
 public static void WriteRecordBySquadId(int id, String record)
 {
     ParameterizedThreadStart p = new ParameterizedThreadStart(WriteRecordBySquadId);
     Thread writeThread = new Thread(p);
     ThreadParams threadParams = new ThreadParams(id, record, syncObject);
     writeThread.Start(threadParams);
 }
Example #9
0
        private void ParameterizedThread(object obj)
        {
            System.Threading.Thread.Sleep(500);

            Int32 rowIndex = 0;

            ThreadParams threadParams = (ThreadParams)obj;

            FormProgress.delCloseForm           deCloseForm           = threadParams.FormProgress.CloseForm;
            FormProgress.delSetBodyText         deSetBodyText         = threadParams.FormProgress.SetBodyText;
            FormProgress.delSetProgressMaximum  deSetProgressMaximum  = threadParams.FormProgress.SetProgressMaximum;
            FormProgress.delSetProgressPosition deSetProgressPosition = threadParams.FormProgress.SetProgressPosition;

            //threadParams.FormProgress.Invoke(deSetBodyText, "Waiting on network...");

            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;

            System.Data.DataTable table = instance.GetDataSources();

            threadParams.FormProgress.Invoke(deSetBodyText, "Populating " + table.Rows.Count + " servers...");
            threadParams.FormProgress.Invoke(deSetProgressMaximum, table.Rows.Count);

            foreach (System.Data.DataRow row in table.Rows)
            {
                SQLServerListObject sqlObject = new SQLServerListObject(row["ServerName"].ToString(),
                                                                        row["InstanceName"].ToString(), row["Version"].ToString(), CBool(row["isClustered"]));

                threadParams.OwnerForm.Invoke(threadParams.AddSQLServerToComboBox, sqlObject);

                threadParams.FormProgress.Invoke(deSetProgressPosition, rowIndex++);
                System.Threading.Thread.Sleep(10);
            }

            threadParams.FormProgress.Invoke(deCloseForm);
        }
Example #10
0
        private void cboServername_DropDown(object sender, EventArgs e)
        {
            if (cboServerName.Items.Count == 0)
            {
                FormProgress FormProgress = new FormProgress();

                System.Threading.Thread thread = new System.Threading.Thread(ParameterizedThread);

                ThreadParams threadParams = new ThreadParams();
                threadParams.OwnerForm              = this;
                threadParams.FormProgress           = FormProgress;
                threadParams.AddSQLServerToComboBox = AddSQLServerToComboBox;

                thread.Start(threadParams);

                FormProgress.EnableCancel(true);

                if (FormProgress.ShowDialog() != DialogResult.OK)
                {
                    if (thread.ThreadState != System.Threading.ThreadState.Stopped)
                    {
                        thread.Abort();
                    }
                }
            }
        }
Example #11
0
        public async Task <IActionResult> GetMessageThread(int userId, [FromQuery] ThreadParams threadParams)
        {
            var sender = await _repo.GetUser(userId);

            if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            if (sender.Id == threadParams.SecondUserId)
            {
                return(BadRequest("User cannot text to himself"));
            }

            var messagesFromRepo = await _repo.GetMessageThread(userId, threadParams);

            if (messagesFromRepo == null)
            {
                return(NoContent());
            }

            var messagesToSend = _mapper.Map <MessageReturnDto[]>(messagesFromRepo);

            Response.AddPagination(messagesFromRepo.CurrentPage,
                                   messagesFromRepo.PageSize,
                                   messagesFromRepo.TotalCount,
                                   messagesFromRepo.TotalPages);

            return(Ok(messagesToSend));
        }
Example #12
0
        public ChunkGenerator()
        {
            Thread generator = new Thread(p =>
            {
                ThreadParams parameters = ((ThreadParams)p);


                BlockingCollection <Chunk> chunkList = parameters.chunkList;

                OpenGL gl = new OpenGL();
                gl.MakeCurrent();

                Glfw.MakeContextCurrent(parameters.window);

                while (parameters.running)
                {
                    chunkList.Take().initialize(gl);
                }
            })
            {
                IsBackground = true
            };

            _parameters = new ThreadParams(_chunkList, Glfw.CreateWindow(1, 1, "", Monitor.None, ToolBox.window));

            generator.Start(_parameters);
        }
Example #13
0
        /// <summary>
        /// Forces the import of the tvguide. Usable when testing the grabber
        /// </summary>
        /// <param name="folder">The folder where tvguide.xml or tvguide.lst is stored</param>
        /// <param name="importXML">True to import tvguide.xml</param>
        /// <param name="importLST">True to import files in tvguide.lst</param>
        public void ForceImport(String folder, bool importXML, bool importLST)
        {
            string fileName = folder + @"\tvguide.xml";

            if (System.IO.File.Exists(fileName) && importXML)
            {
                importXML = true;
            }

            fileName = folder + @"\tvguide.lst";

            if (importLST && System.IO.File.Exists(fileName))
            {
                DateTime fileTime = DateTime.Parse(System.IO.File.GetLastWriteTime(fileName).ToString());
                // for rounding errors!!!
                importLST = true;
            }

            if (importXML || importLST)
            {
                ThreadParams tp = new ThreadParams();
                tp._importDate = DateTime.MinValue;
                tp._importLST  = importLST;
                tp._importXML  = importXML;

                this.ThreadFunctionImportTVGuide(tp);
            }
        }
Example #14
0
            /// <summary>
            /// Adaptive version
            /// </summary>
            /// <param name="o"></param>
            public void Fill_Voxels(object o)
            {
                ThreadParams T = (ThreadParams)o;

                for (int x = T.startvoxel; x < T.endvoxel; x++)
                {
                    for (int y = 0; y < VoxelCtY; y++)
                    {
                        for (int z = 0; z < VoxelCtZ; z++)
                        {
                            Voxel_Inv[x, y, z, T.m] = new List <int>();
                            Point VoxelMin = new Point(x * VoxelDims.x - Epsilon, y * VoxelDims.y - Epsilon, z * VoxelDims.z - Epsilon);
                            Point VoxelMax = new Point((x + 1) * VoxelDims.x + Epsilon, (y + 1) * VoxelDims.y + Epsilon, (z + 1) * VoxelDims.z + Epsilon);
                            AABB  Box      = new AABB(VoxelMin + OBox.Min, VoxelMax + OBox.Min);
                            Voxels[x, y, z] = Box;
                            for (int i = 0; i < Model[T.m].Polygon_Count; i++)
                            {
                                //Check for intersection between voxel x,y,z with Polygon i...
                                if (Box.PolyBoxOverlap(Model[T.m].Polygon_Vertices(i)))
                                {
                                    Voxel_Inv[x, y, z, T.m].Add(i);
                                }
                            }
                            //Check for Null Voxels
                            if (Voxel_Inv[x, y, z, T.m] == null)
                            {
                                System.Windows.Forms.MessageBox.Show("Whoops... Null Voxels Detected");
                            }
                            ///////////////////////
                        }
                    }
                }
            }
Example #15
0
 public void Start <T>(StoreAction <T> store,
                       ActionWithData <T> action,
                       StopCondition <T> closeConnectionCondition) where T : class
 {
     onStart();
     try
     {
         serverSocket.Bind(ipEndPoint);
         serverSocket.Listen(config.MaxConnections);
         ThreadParams <T> param = new ThreadParams <T>(store, action, closeConnectionCondition);
         Thread           connectionListener = new Thread(Listen <T>);
         connectionListener.Start(param);
         string cmd;
         while (true)
         {
             cmd = Console.ReadLine();
             if (cmd.Equals(config.ServerStopCommand))
             {
                 break;
             }
         }
         connectionListener.Abort("Stopping server.");
         connectionListener.Join();
         serverSocket.Shutdown(SocketShutdown.Both);
         serverSocket.Close();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
Example #16
0
        // Get batches to process
        private void SplitBatchThread(object infoObj)
        {
            ThreadParams p         = (ThreadParams)infoObj;
            int          min       = p.min;
            int          max       = p.max;
            int          batchSize = p.batchSize;

            char[] start = new char[min];
            char[] end   = new char[max];

            for (int i = 0; i < start.Length; i++)
            {
                start[i] = validChars.First();
            }
            for (int i = 0; i < end.Length; i++)
            {
                end[i] = validChars.Last();
            }

            List <Tuple <char[], char[]> > b = BreakPass.Split(batchSize, start, end, validChars);

            foreach (Tuple <char[], char[]> t in b)
            {
                batchesNotProcessed.Add(t);
            }

            isReady = true;

            BatchUpdate();
        }
Example #17
0
            private void ExecCmd(object p)
            {
                ThreadParams tp = (ThreadParams)p;

                string readCursor   = null;
                bool   hasOutParams = false;

                foreach (OracleParameter param in tp.cmd.Parameters)
                {
                    if (param.OracleDbType == OracleDbType.RefCursor)
                    {
                        readCursor = param.ParameterName;
                        break;
                    }
                    else
                    {
                        if (param.Direction == ParameterDirection.Output || param.Direction == ParameterDirection.InputOutput)
                        {
                            hasOutParams = true;
                            break;
                        }
                    }
                }

                try
                {
                    if (!String.IsNullOrEmpty(readCursor))
                    {
                        OracleDataAdapter da = new OracleDataAdapter(tp.cmd);
                        DataTable         dt = new DataTable();
                        da.Fill(dt);
                        tp.ResultValue = dt;
                    }
                    else
                    {
                        if (hasOutParams)
                        {
                            tp.cmd.ExecuteNonQuery();
                            Dictionary <string, object> dict = new Dictionary <string, object>();
                            foreach (OracleParameter param in tp.cmd.Parameters)
                            {
                                if (param.Direction == ParameterDirection.Output || param.Direction == ParameterDirection.InputOutput)
                                {
                                    dict.Add(param.ParameterName, param.Value);
                                }
                            }
                            tp.ResultValue = dict;
                        }
                        else
                        {
                            tp.ResultValue = tp.cmd.ExecuteScalar();
                        }
                    }
                }
                catch (Exception e)
                {
                    tp.e = e;
                }
            }
Example #18
0
 public UserControl1(TabControl _tabcontrol1, Playlist _playlist)
 {
     InitializeComponent();
     _sunccontext = SynchronizationContext.Current;
     tabcontrol1 = _tabcontrol1;
     tp = new ThreadParams() { player = this, command = PlayingCommand.Stop, playlist = _playlist, isTerminate = false, doStep = 0 };
     th.IsBackground = true;
     th.Start(tp);
 }
Example #19
0
 private void Cleanup(ThreadParams state)
 {
     Console.WriteLine($"{prefix}Doing clean up tasks. Thread {state.ThreadIndex}");
     state.ClientSocket.Shutdown(SocketShutdown.Both);
     state.ClientSocket.Close();
     state.ClientSocket.Dispose();
     ReceivedBuffer = new byte[StorageSize];
     state.ThreadHandle.Set();
 }
Example #20
0
        public void PutInNewItem(Action <object> action, object o)
        {
            ThreadParams param = new ThreadParams()
            {
                Action = action, Parameter = o
            };

            threadPool.Enqueue(param);
        }
Example #21
0
        private void EnqueueThreadItem(object threadParams)
        {
            ThreadParams param = threadParams as ThreadParams;

            //param.Action(param.Parameter);
            ThreadPool.QueueUserWorkItem(new WaitCallback(param.Action), param.Parameter);//由于客户端与服务端数据交互较频繁,用线程池进行每次通信任务的处理
            //Thread thread = new Thread(new ParameterizedThreadStart(param.Action));
            //thread.Start(param.Parameter);
            //thread.Join();
        }
Example #22
0
 public void InitializeCloud()
 {
     visibleClouds    = new int[CloudSystem.instance.maxClouds];
     visibleParticles = new int[CloudSystem.instance.maxParticles];
     maxMeshParticles = CloudSystem.instance.maxParticles / 4;
     vertices         = new Vector3[maxMeshParticles * 4];
     colors           = new Color32[maxMeshParticles * 4];
     particleSort     = new ParticleSort[CloudSystem.instance.maxParticles];
     myThreads        = new int[CloudSystem.instance.maxThreadCount];
     if (helperThreads == null)
     {
         helperThreads = new Thread[CloudSystem.instance.maxThreadCount];
         helperParams  = new ThreadParams[CloudSystem.instance.maxThreadCount];
         for (int i = 0; i < CloudSystem.instance.maxThreadCount; i++)
         {
             helperThreads[i] = new Thread(Worker);
             helperParams[i]  = new ThreadParams
             {
                 start          = maxMeshParticles / CloudSystem.instance.threadCount * (i % CloudSystem.instance.threadCount),
                 end            = maxMeshParticles / CloudSystem.instance.threadCount * (i % CloudSystem.instance.threadCount + 1),
                 running        = (i < CloudSystem.instance.threadCount),
                 abort          = false,
                 verts          = vertices,
                 cols           = colors,
                 psort          = particleSort,
                 vpCount        = visibleParticlesCount,
                 startHandle    = new AutoResetEvent(initialState: false),
                 completeHandle = new AutoResetEvent(initialState: false)
             };
             myThreads[i] = ((i >= CloudSystem.instance.threadCount) ? (-1) : i);
             helperThreads[i].Start(helperParams[i]);
         }
         return;
     }
     for (int j = 0; j < CloudSystem.instance.threadCount; j++)
     {
         myThreads[j] = -1;
         for (int k = 0; k < CloudSystem.instance.maxThreadCount; k++)
         {
             if (!helperParams[k].running)
             {
                 helperParams[k].start   = maxMeshParticles / CloudSystem.instance.threadCount * j;
                 helperParams[k].end     = maxMeshParticles / CloudSystem.instance.threadCount * (j + 1);
                 helperParams[k].abort   = false;
                 helperParams[k].verts   = vertices;
                 helperParams[k].cols    = colors;
                 helperParams[k].psort   = particleSort;
                 helperParams[k].vpCount = visibleParticlesCount;
                 myThreads[j]            = k;
                 helperParams[k].running = true;
                 break;
             }
         }
     }
 }
        //                              NOTE: Process "hg" is not in list, because it causes only low CPU load

        public static void StartController(ProcessPriorityClass priority, OutputManager outputManager)
        {
            ThreadParams threadParams = new ThreadParams(priority, outputManager);

            Thread controllerThread = new Thread(new ParameterizedThreadStart(ControlThread.DoWork));

            controllerThread.IsBackground = true; // stop thread when main thread stops
            controllerThread.Start(threadParams);

            outputManager.Info("Priority for worker processes:  " + priority.ToString());
        }
Example #24
0
        private void ExecuteThreadPool()
        {
            //custom thread parameter object
            ThreadParams tParams = new ThreadParams();

            //get the file name from command prompt - user input
            tParams.sourceFileName = labelFilePath.Text;

            //queue the file copy thread for execution
            ThreadPool.QueueUserWorkItem(new WaitCallback(readFileThreadPool), tParams);
        }
Example #25
0
        private static void ThreadActivateTheme(object param)
        {
            if (!(param is ThreadParams))
            {
                Log.Error("param at ThreadActivateTheme has wrong type");
                return;
            }
            ThreadParams threadParams = (ThreadParams)param;

            GUIWaitCursor.Show();

            // Need to initialize fonts and references if they change based on the theme.
            // Check current theme.
            bool initFonts      = (GUIGraphicsContext.HasThemeSpecificSkinFile(@"\fonts.xml"));
            bool initReferences = (GUIGraphicsContext.HasThemeSpecificSkinFile(@"\references.xml"));

            // Change the theme and save this new setting.
            SetTheme(threadParams._themeName);
            SkinSettings.Save();

            // Check new theme.
            initFonts      = initFonts || GUIGraphicsContext.HasThemeSpecificSkinFile(@"\fonts.xml");
            initReferences = initReferences || GUIGraphicsContext.HasThemeSpecificSkinFile(@"\references.xml");

            // Reset fonts if needed.
            if (initFonts)
            {
                // Reinitializing the device while changing fonts freezes the UI.
                // Add some sleep() to present the wait cursor animation for at least some user feedback.
                Thread.Sleep(500);
                GUIFontManager.ClearFontCache();
                GUIFontManager.LoadFonts(GUIGraphicsContext.GetThemedSkinFile(@"\fonts.xml"));
                GUIFontManager.InitializeDeviceObjects();
                Thread.Sleep(500);
            }

            // Force a reload of the control references if needed.
            if (initReferences)
            {
                GUIControlFactory.ClearReferences();
            }

            // Reactivate the current window and refocus on the control used to change the theme.
            // This applies the new theme to the current window immediately.
            GUIWindowManager.ResetAllControls();
            GUIWindowManager.SendThreadCallbackAndWait((p1, p2, p3) =>
            {
                GUIWindowManager.ActivateWindow(p1, true, true, (int)p3);
                return(0);
            }, GUIWindowManager.ActiveWindow, 0, threadParams._focusControlId);

            GUIWaitCursor.Hide();
        }
Example #26
0
        public async Task <PagedList <Message> > GetMessageThread(int requestorId, ThreadParams threadParams)
        {
            var messagesThread = _context.Messages.Where(x =>
                                                         (x.RecipientId == requestorId && x.SenderId == threadParams.SecondUserId) ||
                                                         (x.RecipientId == threadParams.SecondUserId && x.SenderId == requestorId))
                                 .Include(x => x.Sender)
                                 .Include(x => x.Recipient)
                                 .OrderByDescending(x => x.MessageSent);

            var massage = await messagesThread.ToListAsync();

            return(await PagedList <Message> .CreateAsync(messagesThread, threadParams.PageNumber, threadParams.PageSize));
        }
Example #27
0
        private void ExecuteTask()
        {
            ThreadParams p = (ThreadParams)_params;

            if (p.isPOST)
            {
                p.outStatus = _webExchange.HttpPost(p.hostName, p.model, p.deviceID, p.action, p.file, out p.outResponse, p.timeout);
            }
            else
            {
                p.outStatus = _webExchange.HttpGet(p.hostName, p.model, p.deviceID, p.action, out p.outResponse, p.extraParams, p.timeout);
            }

            _isDone.Set();
        }
    void CalculatePopulationFitnessNonThreaded()
    {
        ResetFitnessValue();
        battles = 0;

        ThreadParams threadParams = new ThreadParams(0, populationSize - 1);

        threadParams.currentHandle = new ManualResetEvent(false);
        BattleWork(threadParams);

        //Sort highest fitness value to lowest
        population.Sort((creatureA, creatureB) => creatureB.fitnessValue.CompareTo(creatureA.fitnessValue));

        totalFitness = battles;
    }
Example #29
0
        public static string ActivateThemeByName(string themeName, int focusControlId)
        {
            // Change themes in a background thread so that the wait cursor gets presented during the theme change.
            ThreadParams threadParams = new ThreadParams()
            {
                _themeName = themeName, _focusControlId = focusControlId
            };

            Thread ActivateThemeThread = new Thread(new ParameterizedThreadStart(ThreadActivateTheme));

            ActivateThemeThread.Name         = "Activate theme for skin";
            ActivateThemeThread.IsBackground = true;
            ActivateThemeThread.Priority     = ThreadPriority.Normal;
            ActivateThemeThread.Start(threadParams);
            return(themeName);
        }
Example #30
0
        static void DoWork(object param)
        {
            ThreadParams _params   = param as ThreadParams;
            string       _imageUrl = _params.ImageUrl;

            if (string.IsNullOrEmpty(_imageUrl))
            {
                return;
            }

            bool _doIt = true;

            if (_params.Movie != null)
            {
                // if the ResultMovieItem needs to do something before querying data...execute and wait for event
                if (_params.Movie.DataQuerying != null)
                {
                    _params.Movie.DataQuerying(_params.Movie, new EventArgs());
                }

                // if Movie has DataReady event not null, wait for it (max 10 seconds)
                if (_params.Movie.DataReadyEvent != null)
                {
                    _doIt = _params.Movie.DataReadyEvent.WaitOne(10000);
                    _params.Movie.DataReadyEvent = null;
                }
            }

            BitmapImage _bmp = null;

            if (_doIt)
            {
                _bmp = DownloadImageFromUrl(_imageUrl);
            }

            _params.Dispatcher.Dispatcher.BeginInvoke((Action) delegate
            {
                if (_params.Handler != null)
                {
                    try
                    {
                        _params.Handler(_bmp, _params.ImageUrl, _params.Dispatcher);
                    }
                    catch { }
                }
            }, DispatcherPriority.Normal);
        }
        public static void CalculatePartitionResult(object stateParams)
        {
            ThreadParams thrParams = (ThreadParams)stateParams;

            int            start = thrParams.start;
            int            end   = thrParams.end;
            int            n     = thrParams.nCount;
            AngryComboDict dict  = thrParams.dict;
            long           count = 0;//thrParams.Count;

            for (int i = start; i <= end; i++)
            {
                //  lstSafeCombinations.Add(new List<string>());
                bool skipAhead = false;
                //                string items = "";
                for (int j = i + 1; j <= n; j++)
                {
                    //for(int k=i; k < j; k++)
                    //{
                    //if (!dict.KeyExists(k))
                    //{
                    //    break;
                    //}

                    //find limit between i and j so that it can be verified and loop is skipped

                    if (dict.KeyValuePairExistsMinMax(j, i))
                    {
                        skipAhead = true;
                        break;
                    }
                    //}

                    if (!skipAhead)
                    {
                        count = count + 1;
                        //       lstSafeCombinations[i - 1].Add("--"+j.ToString());
                    }
                    else
                    {
                        break;
                    }
                }
            }

            thrParams.Count = count;
        }
Example #32
0
        // constructor, will start worker handling
        public HandleWorkers(int min, int max, int batchSize, string fileName, bool lower, bool upper, bool numbers, bool symbols)
        {
            isReady = false;

            lowerChars  = lower;
            upperChars  = upper;
            numberChars = numbers;
            symbolChars = symbols;

            validChars = new List <char>();
            if (lower)
            {
                validChars.AddRange(BreakPass.lowerCaseChars);
            }
            if (upper)
            {
                validChars.AddRange(BreakPass.upperCaseChars);
            }
            if (numbers)
            {
                validChars.AddRange(BreakPass.numberChars);
            }
            if (symbols)
            {
                validChars.AddRange(BreakPass.symbolChars);
            }

            batchesNotProcessed = new ConcurrentBag <Tuple <char[], char[]> >();
            batchesProcessed    = new ConcurrentBag <Tuple <char[], char[]> >();
            bathcesProcessing   = new ConcurrentBag <Tuple <char[], char[]> >();

            ThreadParams p = new ThreadParams();

            p.min       = min;
            p.max       = max;
            p.batchSize = batchSize;

            Thread splitThread = new Thread(new ParameterizedThreadStart(SplitBatchThread));

            splitThread.SetApartmentState(ApartmentState.STA);
            splitThread.Start(p);

            doWork     = true;
            workThread = new Thread(new ParameterizedThreadStart(DoWorkThread));
            workThread.Start(fileName);
        }
Example #33
0
        private void Listen <T>(object obj) where T : class
        {
            if (obj == null)
            {
                throw new ArgumentNullException();
            }
            ThreadParams <T> param = obj as ThreadParams <T>;

            if (param == null)
            {
                throw new InvalidCastException("Cannot cast " + obj + " to ThreadParams<" + typeof(T) + ">");
            }
            try
            {
                while (true)
                {
                    Console.WriteLine("Waiting for a connection via port {0}", ipEndPoint);
                    Socket handler = serverSocket.Accept();
                    Console.WriteLine("Server set connection with {0}", handler.LocalEndPoint);
                    byte[] bytes = new byte[config.BufferSize];
                    int    bytesRecieved;
                    T      data = null;
                    while (handler.Available > 0)
                    {
                        bytesRecieved = handler.Receive(bytes);
                        data          = param.store(bytes, bytesRecieved, data);
                    }
                    beforeDataManipulates();
                    data = param.action(data);
                    afterDataManipulates();
                    if (param.closeConnectionCondition(data))
                    {
                        Console.WriteLine("Server closed the connection with client: {0}", handler.LocalEndPoint);
                        onCloseConnection();
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine(e.ExceptionState);
                onStop();
            }
        }
        /// <summary>
        /// Decodes entities to be of the given type by using a list of json strings and a type
        /// It is Multithreaded for faster efficiency
        /// </summary>
        /// <param name="json">A list of json strings</param>
        /// <param name="type">the entity type (case insensitive)</param>
        /// <returns>An array of entities built from JSON</returns>
#else
        /// <summary>
        /// Decodes entities to be of the given type by using a list of json strings and a type
        /// </summary>
        /// <param name="json">A list of json strings</param>
        /// <param name="type">the entity type (case insensitive)</param>
        /// <returns>An array of entities built from JSON</returns>
#endif
        public static Entity[] Decode(List<String> json, String type)
        {
            Entity[] entities = new Entity[json.Count];

            CreateEntity entityCreator = GetEntityCreator(type);

            int index = 0;
#if THREAD_SAFE
            Thread[] threads = new Thread[json.Count];
            ThreadParams[] threadParams = new ThreadParams[json.Count];
#endif
            foreach (String j in json)
            {
#if THREAD_SAFE
                ThreadParams param = new ThreadParams();
                threadParams[index] = param;
                param.json = j;
                param.createFunc = entityCreator;
                threads[index] = StartThread(param);
#else

                JsonDeserializer deserializer = new JsonDeserializer();
                entities[index] = entityCreator(j, deserializer);
#endif
                ++index;
            }

#if THREAD_SAFE
            for(index = 0; index < threads.Length; ++index)
            {
                threads[index].Join();
                entities[index] = threadParams[index].entity;
            }
#endif
            return entities;
        }
Example #35
0
        /// <summary>
        /// Search files asynchronously
        /// </summary>
        /// <param name="folder">The folder where to begin searching.</param>
        /// <param name="pattern">The pattern the files need to match (ex. *.txt).</param>
        /// <param name="includeSubfolders">Specifies whether or not to search the subfolders.</param>
        public void SearchFilesAsync(string folder, string pattern, bool regexPattern, bool includeSubfolders)
        {
            Thread t = new Thread(SearchAsync);
            t.Name = "SearchThread";

            ThreadParams param = new ThreadParams();
            param.folder = folder;
            param.pattern = pattern;
            param.regexPattern = regexPattern;
            param.includeSubfolders = includeSubfolders;

            t.Priority = ThreadPriority.BelowNormal;
            t.Start(param);
        }
		public static void ApplyOptions(MainViewModel model, bool ApplyingToCurrentUserAsAdmin = false)
		{
			bool IsAdminUser = (model.AppModel.IsAdmin && !ApplyingToCurrentUserAsAdmin);
			Thread th = new Thread(new ParameterizedThreadStart(ApplyOptionsThreadProc));
			th.SetApartmentState(ApartmentState.STA);
			var threadParams = new ThreadParams()
			{
				model = model,
				IsAdmin = IsAdminUser
			};
			th.Start(threadParams);
			th.Join();
			// marshal the exception back to the UI thread - up to calling code to deal with it.
			if (threadParams.Exception != null)
				throw threadParams.Exception;
		}
 /// <summary>
 /// This starts a new thread that will parse and create an object; useful for large objects/json
 /// by having this in it's own function, the lambda function will use the function closure to get the correct variables
 /// </summary>
 /// <param name="param">The thread params to use</param>
 /// <returns>The thread that was started</returns>
 private static Thread StartThread(ThreadParams param)
 {
     Thread t = new Thread(() => { param.entity = param.createFunc(param.json, new JsonDeserializer()); });
     t.Start();
     return t;
 }
Example #38
0
    protected void StartImport(WebEPG.ShowProgressHandler showProgress)
    {
      if (_workerThreadRunning)
        return;


      _workerThreadRunning = true;
      ThreadParams param = new ThreadParams();
      param.showProgress = showProgress;
      Thread workerThread = new Thread(new ParameterizedThreadStart(ThreadFunctionImportTVGuide));
      workerThread.Name = "WebEPGImporter";
      workerThread.IsBackground = true;
      workerThread.Priority = ThreadPriority.Lowest;
      workerThread.Start(param);
    }
Example #39
0
    /// <summary>
    /// Forces the import of the tvguide. Usable when testing the grabber
    /// </summary>
    /// <param name="folder">The folder where tvguide.xml or tvguide.lst is stored</param>
    /// <param name="importXML">True to import tvguide.xml</param>
    /// <param name="importLST">True to import files in tvguide.lst</param>
    public void ForceImport(String folder, bool importXML, bool importLST)
    {
      string fileName = folder + @"\tvguide.xml";

      if (System.IO.File.Exists(fileName) && importXML)
      {
        importXML = true;
      }

      fileName = folder + @"\tvguide.lst";

      if (importLST && System.IO.File.Exists(fileName))
      {
        DateTime fileTime = DateTime.Parse(System.IO.File.GetLastWriteTime(fileName).ToString());
        // for rounding errors!!!
        importLST = true;
      }

      if (importXML || importLST)
      {
        ThreadParams tp = new ThreadParams();
        tp._importDate = DateTime.MinValue;
        tp._importLST = importLST;
        tp._importXML = importXML;

        this.ThreadFunctionImportTVGuide(tp);
      }
    }
Example #40
0
    protected void StartImport(bool importXML, bool importLST, DateTime importDate)
    {
      FileStream streamIn = null;
      StreamReader fileIn = null;
      if (_workerThreadRunning)
        return;

      TvBusinessLayer layer = new TvBusinessLayer();
      string folder = layer.GetSetting("xmlTv", DefaultOutputFolder).Value;

      Thread.Sleep(500); // give time to the external prog to close file handle

      if (importXML)
      {
        string fileName = folder + @"\tvguide.xml";

        try
        {
          //check if file can be opened for reading....
          IOUtil.CheckFileAccessRights(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        }
        catch (Exception e)
        {
          Log.Error(@"plugin:xmltv StartImport - File [" + fileName + "] doesn't have read access : " + e.Message);
          return;
        }
      }

      if (importLST)
      {
        string fileName = folder + @"\tvguide.lst";

        try
        {
          IOUtil.CheckFileAccessRights(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        }
        catch (Exception e)
        {
          Log.Error(@"plugin:xmltv StartImport - File [" + fileName + "] doesn't have read access : " + e.Message);
          return;
        }
        try //Check that all listed files can be read before starting import (and deleting programs list)
        {
          Encoding fileEncoding = Encoding.Default;
          streamIn = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
          fileIn = new StreamReader(streamIn, fileEncoding, true);
          while (!fileIn.EndOfStream)
          {
            string tvguideFileName = fileIn.ReadLine();
            if (tvguideFileName.Length == 0) continue;

            if (!System.IO.Path.IsPathRooted(tvguideFileName))
            {
              // extend by directory
              tvguideFileName = System.IO.Path.Combine(folder, tvguideFileName);
            }
            try
            {
              IOUtil.CheckFileAccessRights(tvguideFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception e)
            {
              Log.Error(@"plugin:xmltv StartImport - File [" + tvguideFileName + "] doesn't have read access : " +
                        e.Message);
              return;
            }
          }
        }
        finally
        {
          if (streamIn != null)
          {
            streamIn.Close();
            streamIn.Dispose();
          }
          if (fileIn != null)
          {
            fileIn.Close();
            fileIn.Dispose();
          }
        }
      }

      _workerThreadRunning = true;
      ThreadParams param = new ThreadParams();
      param._importXML = importXML;
      param._importLST = importLST;
      param._importDate = importDate;
      Thread workerThread = new Thread(new ParameterizedThreadStart(ThreadFunctionImportTVGuide));
      workerThread.Name = "XmlTvImporter";
      workerThread.IsBackground = true;
      workerThread.Priority = ThreadPriority.Lowest;
      workerThread.Start(param);
    }