Example #1
1
        public void Execute(string[] args)
        {
            Options options = new Options(args);

            int threadsCount = options.ThreadsCount > 0
                ? options.ThreadsCount
                : Environment.ProcessorCount;

            _loopsPerThread = options.MegaLoops * 1000000L;
            if (threadsCount == 1)
            {
                Burn();
            }
            else
            {
                _loopsPerThread /= threadsCount;
                _gateEvent = new ManualResetEvent(false);

                Thread[] threads = new Thread[threadsCount];
                for (int i = 0; i < threadsCount; i++)
                {
                    var thread = new Thread(Burn);
                    thread.IsBackground = true;
                    thread.Start();
                    threads[i] = thread;
                }
                _gateEvent.Set();

                foreach (var thread in threads)
                    thread.Join();
            }
        }
Example #2
1
        static void Main(string[] args)
        {
            int [] mas = {5,15};
            ThreadManipulator Manipulator = new ThreadManipulator();
            Thread Thread_AddingOne1 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingOne2 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingCustomValue = new Thread(Manipulator.AddingCustomValue);

            Thread Thread_Stop = new Thread(Manipulator.Stop);
            Thread_Stop.IsBackground = true;

            Console.WriteLine("Enter q for braking thream1 and w for thream2");

            Thread_AddingOne1.Start(10);
            Thread_AddingOne2.Start(20);
            Thread_AddingCustomValue.Start(mas);

            Thread_Stop.Start();

            Thread_AddingOne1.Join();
            Thread_AddingOne2.Join();
            Thread_AddingCustomValue.Join();
            Thread_Stop.Join();

            Console.ReadKey();

        }
 public static int Main()
 {
     Thread
     t1
     =
     new
     Thread(new
     ThreadStart
     (MultiThreadExceptionTest.ThreadStart1));
     t1.Name
     =
     "Thread 1";
     Thread.Sleep
     (100);
     t1.Start();
     Thread.Sleep
     (200);
     t1.Abort
     ("STATETEST");
     t1.Join
     ();
     Console.WriteLine
     ("Result: "
     +
     result);
     if
     (result
     !=
     27)
     return
     1;
     return
     0;
 }
        public void TestConcurrentQueueDeclare()
        {
            string x = GenerateExchangeName();
            Random rnd = new Random();

            List<Thread> ts = new List<Thread>();
            System.NotSupportedException nse = null;
            for(int i = 0; i < 256; i++)
            {
                Thread t = new Thread(() =>
                        {
                            try
                            {
                                // sleep for a random amount of time to increase the chances
                                // of thread interleaving. MK.
                                Thread.Sleep(rnd.Next(5, 500));
                                Model.ExchangeDeclare(x, "fanout", false, false, null);
                            } catch (System.NotSupportedException e)
                            {
                                nse = e;
                            }
                        });
                ts.Add(t);
                t.Start();
            }

            foreach (Thread t in ts)
            {
                t.Join();
            }

            Assert.IsNotNull(nse);
            Model.ExchangeDelete(x);
        }
Example #5
1
        /*
        * Reads all INFATI data and fills out all possible fields in the database
        */
        static void UpdateDatabaseThreaded()
        {
            List<Worker> workerPool = new List<Worker>();

            for (Int16 i = 1; i <= 1; i++) {
                workerPool.Add(new Worker(1, i));
            }

            /*
            for (Int16 i = 12; i <= 20; i++) {
                workerPool.Add(new Worker(2, i));
            }
            */
            List<Thread> threads = new List<Thread>();
            foreach (Worker worker in workerPool) {
                Thread thread = new Thread(new ThreadStart(worker.Start));
                thread.Start();
                threads.Add(thread);
            }

            foreach (var thread in threads) {
                thread.Join();
            }

            Console.WriteLine("All threads ended");
        }
 static void RunWithTimeout(Action entryPoint, int timeout)
 {
     Thread thread = null;
     try
     {
          thread = new Thread(() => entryPoint()) { IsBackground = true };
         if (thread != null)
         {
             thread.Start();
             if(thread.IsAlive)
                 thread.Join(timeout);
         }
     }
     catch (Exception ex) { ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, null, "ошибка запуска задания " + ex.Message,-1); }
     finally
     {
         if (thread != null)
             thread.Abort();
         if (thread != null)
             thread.Join(3000);
         if (thread != null)
             thread.Interrupt();
         if (thread != null)
             GC.SuppressFinalize(thread);
     };
     thread = null;
 }
Example #7
0
        public override void FolderFinishedHandler(Item item)
        {
            try
            {
                m_thread = new Thread(this.RetreiveData);
                m_thread.Name = "Tree Thread";
                m_thread.Start();
                m_thread.Join();

                m_tree.Dispatcher.Invoke(() =>
                {
                    if (m_itemsStack.Peek().Header.ToString() == item.Name)
                    {
                        m_itemsStack.Pop();
                    }
                    else
                    {
                        throw new Exception(string.Format("invalid element structure {0} != {1}", m_itemsStack.Peek(), item.Id));
                    }
                });
            }
            catch (Exception exc)
            {
                m_thread.Abort();
                m_thread.Join();
                OnExceptionOccured(exc.Message);
            }
        }
        static void Main()
        {
            var clock = new Thread(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                    Thread.Sleep(500);
                }

            }) { IsBackground = true };

            // --- BACKGROUND THREAD EXPLANATION ---
            // Case 1 -- START
            clock.Start();
            // Result: It never prints anything, i.e. Background threads can't keep a
            // process alive until it exits.
            // Case 1 -- END

            // Case 2 -- START
            clock.Start();
            Thread.Sleep(2000);
            // Result: Prints four times, i.e. 0\n1\n2\n3
            // Case 2 -- END

            // Case 3 -- START
            clock.Start();
            clock.Join();
            // Result: Prints all values, because the foreground thread (in Main method)
            // waits for the end of the execution of the clock thread with a help of
            // 'Join' method
            // Case 3 -- END
            // --- BACKGROUND THREAD EXPLANATION END ---

            // --- FOREGROUND THREAD EXPLANATION ---
            clock.IsBackground = false;
            // Case 1 -- START
            clock.Start();
            // Result: Prints all values, because the foreground thread can keep a
            // process alive until it exits. All new threads are foreground by default
            // Case 1 -- END

            // Case 2 -- START
            clock.Start();
            Thread.Sleep(2000);
            // Result: Prints all values.
            // Case 2 -- END

            // Case 3 -- START
            clock.Start();
            clock.Join();
            // Result: Prints all values.
            // Case 3 -- END
            // --- FOREGROUND THREAD EXPLANATION END ---
        }
        public void should_wait_for_completion()
        {
            var thread = new Thread(() => _defaultCompletionCallback.WaitForCompletion());
            thread.Start();

            Assert.False(thread.Join(300));

            _defaultCompletionCallback.ExecuteCallback(new CompletionAcknowledgementMessage(Guid.NewGuid(),"test", true, null));

            Assert.IsTrue(thread.Join(300));
        }
        /// <summary>
        /// Attempts to terminate the passed in thread
        /// </summary>
        /// <param name="workerThread">The worker thread.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns></returns>
        public bool AttemptToTerminate(Thread workerThread, TimeSpan? timeout)
        {
            if (workerThread == null || !workerThread.IsAlive)
                return true; //if the thread is null or not alive, its terminated

            if (timeout.HasValue)
            {
                return workerThread.Join(timeout.Value);
            }
            workerThread.Join();
            return true;
        }
Example #11
0
        public void CabinetMultithread()
        {
            this.multithreadExceptions = new List<Exception>();

            const int threadCount = 10;
            IList<Thread> threads = new List<Thread>(threadCount);

            for (int i = 0; i < threadCount; i++)
            {
                Thread thread = new Thread(new ThreadStart(this.CabinetMultithreadWorker));
                thread.Name = "CabinetMultithreadWorker_" + i;
                threads.Add(thread);
            }

            foreach (Thread thread in threads)
            {
                thread.Start();
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            foreach (Exception ex in this.multithreadExceptions)
            {
                Console.WriteLine();
                Console.WriteLine(ex);
            }
            Assert.AreEqual<int>(0, this.multithreadExceptions.Count);
        }
Example #12
0
        private void rellenaArrays_Click(object sender, EventArgs e)
        {
            Thread t1 = new Thread(rellena);
            Thread t2 = new Thread(rellena);
            Thread t3 = new Thread(rellena);
            Thread t4 = new Thread(rellena);
            Thread t5 = new Thread(rellena);

            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();

            //Thread.Sleep(10000);

            //Esperar fin ejecución de todos los threads

            t1.Join();
            t2.Join();
            t3.Join();
            t4.Join();
            t5.Join();


            //ver array

            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(i + ".- " + numeros[i]);
            }
        }
Example #13
0
        private void btnArrays_Click(object sender, EventArgs e)
        {
            Thread t1 = new Thread(rellenaArr1);
            Thread t2 = new Thread(rellenaArr2);

            t1.Start();
            t2.Start();

            t1.Join();
            t2.Join();

            Thread t3 = new Thread(circularArray);
            t3.Priority = ThreadPriority.AboveNormal;

            t3.Start();

            poolThread[0] = new Thread(intercambiarImpar);
            poolThread[1] = new Thread(intercambiarImpar);
            poolThread[2] = new Thread(intercambiarImpar);

            poolThread[0].Start();
            poolThread[1].Start();
            poolThread[2].Start();

        }
Example #14
0
        // Выделение связных областей рекурсивным алгоритмом
        unsafe private void AllocationOfConnectedDomains_recursively()
        {
            int maxStackSize = 100000000;
            Bitmap tmp = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat);

            Thread t = new Thread(() =>
            {              
                UnsafeBitmap src = new UnsafeBitmap(tmp);
                Byte* pBaseSrc = src.LockBitmap();
                int L = 1;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        FillLabels(pBaseSrc, x, y, L++);
                    }
                }
                src.UnlockBitmap();
            }, maxStackSize);

            t.Start();
            t.Join();

            objectsCount = RenumberDomains();            
        }
        public void ShouldCallExceptionHandlerOnUncaughtException()
        {
            var ex = new Exception();
            var exceptionHandlerMock = new Mock<IExceptionHandler<object>>();
            _batchEventProcessor.SetExceptionHandler(exceptionHandlerMock.Object);

            _batchHandlerMock.Setup(bh => bh.OnEvent(_ringBuffer[0], 0, true))
                             .Throws(ex); // OnNext raises an expcetion

            exceptionHandlerMock.Setup(bh => bh.HandleEventException(ex, 0, _ringBuffer[0]))
                             .Callback(() => _countDownEvent.Signal()); // Exception should be handled here and signal the CDE

            var thread = new Thread(_batchEventProcessor.Run);
            thread.Start();

            _ringBuffer.Publish(_ringBuffer.Next());

            _countDownEvent.Wait(50);

            _batchEventProcessor.Halt();
            thread.Join();

            _batchHandlerMock.VerifyAll();
            exceptionHandlerMock.VerifyAll();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Session["MainUrl"].ToString();
            }
            catch (NullReferenceException)
            {
                Response.Redirect("~/");
                return;
            }
            Debug.WriteLine(">>>> CodeQuality");

            this.sitemap = (List<string>)Session["selectedSites"];

            var ths = new ThreadStart(TestCodeQuality);
            var th = new Thread(ths);
            th.Start();

            th.Join();

            var sb = new System.Text.StringBuilder();
            CodeQualitySession.RenderControl(new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter(sb)));
            string htmlstring = sb.ToString();

            Session["CodeQuality"] = htmlstring;
        }
Example #17
0
 private int Run()
 {
     int iRet = -1;
     Console.WriteLine("Abandoning only one Mutex in array " +
         "with other WaitHandles, signaling other mutexes");
     CreateArray(64);
     Thread t = new Thread(new ThreadStart(this.AbandonOneAndRelease));
     t.Start();
     t.Join();
     int i = -1;
     try
     {
         Console.WriteLine("Waiting...");
         i = WaitHandle.WaitAny(wh);
         Console.WriteLine("WaitAny did not throw AbandonedMutexExcpetion");
     }
     catch(AbandonedMutexException)
     {
         // Expected
         iRet = 100;
     }
     catch(Exception e)
     {
         Console.WriteLine("Unexpected exception thrown: " + 
             e.ToString());
     }
     Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
     return iRet;
 }
        public string StopRecording(String recordingDate, bool download)
        {
            camera.CloseShutter();

            Video video = camera.Contents().VideosAsync().Result.LastOrDefault();

            if (download)
            {
                // Create the thread object. This does not start the thread.
                GoProDownloader downloader = new GoProDownloader(camera, recordingDate);
                Thread downloaderThread = new Thread(downloader.Download);

                // Start the worker thread.
                downloaderThread.Start();
                Console.WriteLine("main thread: Starting worker thread...");

                // Loop until worker thread activates.
                while (!downloaderThread.IsAlive)
                {
                    ;
                }

                downloaderThread.Join();

                if (!downloader.successful)
                {
                    throw new Exception("Unsuccessful download");
                }
            }

            return video.Name;
        }
Example #19
0
        private static string ScreenCaptureInStaThread(string received, Action screenCapture)
        {
            Exception caught = null;
            var t = new Thread(() =>
            {
                try
                {
                    screenCapture();
                }
                catch (Exception e)
                {
                    caught = e;
                }
            });

            t.SetApartmentState(ApartmentState.STA); //Many WPF UI elements need to be created inside STA
            t.Start();
            t.Join();

            if (caught != null)
            {
                throw new Exception("Creating window failed.", caught);
            }

            return received;
        }
Example #20
0
        public void Execute()
        {
            this.Config.LiveReloadScript = "<script type=\"text/javascript\" src=\"http://livejs.com/live.js\"></script>";

            var thread = new Thread(RenderThread);

            try
            {
                using (var documentsWatcher = this.CreateWatcher(this.Config.DocumentsPath))
                using (var filesWatcher = this.CreateWatcher(this.Config.FilesPath))
                using (var layoutsWatcher = this.CreateWatcher(this.Config.LayoutsPath))
                {
                    documentsWatcher.EnableRaisingEvents = true;
                    filesWatcher.EnableRaisingEvents = true;
                    layoutsWatcher.EnableRaisingEvents = true;

                    thread.Start(this);

                    var serve = new RunServeCommand();
                    serve.Config = this.Config;
                    serve.Execute();
                }
            }
            finally
            {
                this.Waits[(int)EventTypes.EndWatch].Set();
                thread.Join();
            }
        }
Example #21
0
        static void Main(string[] args)
        {
            UdpNotifierCacheDependency dependency = new UdpNotifierCacheDependency();

            ObjectCacheQueue.Instance.Add("ClientData", string.Empty, dependency);

            object oldCacheData = ObjectCacheQueue.Instance["ClientData"];

            Console.Title = "UdpCacheDependency测试Chat";

            Console.WriteLine("Please input text...");

            Thread thread = new Thread((ThreadStart)MonitorThread);

            thread.Start();

            string cmd = Console.ReadLine();

            while (cmd.ToLower() != "exit")
            {
                if (cmd.IsNotEmpty())
                {
                    if (cmd.ToLower() == "send100")
                        SendOneHundredMessages();
                    else
                        SendOneMessage(cmd);
                }

                cmd = Console.ReadLine();
            }

            thread.Abort();
            thread.Join();
        }
        public void RegisterClassWithoutDependencyMethod_Fail()
        {
            var c = new Container();
            c.RegisterType<EmptyClass>().AsSingleton();
            c.RegisterType<SampleClassWithoutClassDependencyMethod>();
            SampleClassWithoutClassDependencyMethod sampleClass = null;
            Exception exception = null;

            var thread = new Thread(() =>
            {
                try
                {
                    sampleClass = c.Resolve<SampleClassWithoutClassDependencyMethod>(ResolveKind.FullEmitFunction);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            });
            thread.Start();
            thread.Join();

            if (exception != null)
            {
                throw exception;
            }

            Assert.IsNotNull(sampleClass);
            Assert.IsNull(sampleClass.EmptyClass);
        }
Example #23
0
        public static void Main(String[] Args)
        {
            QConnection q = new QBasicConnection(Args.Length >= 1 ? Args[0] : "localhost",
                                                 Args.Length >= 2 ? int.Parse(Args[1]) : 5001, null, null);
            try
            {
                q.Open();
                Console.WriteLine("conn: " + q + "  protocol: " + q.ProtocolVersion);
                Console.WriteLine("WARNING: this application overwrites: .u.upd function on q process");
                Console.WriteLine("Press <ENTER> to close application");
                q.Sync(".u.upd:{[x;y] show (x;y)};");

                PublisherTask pt = new PublisherTask(q);
                Thread workerThread = new Thread(pt.Run);
                workerThread.Start();

                Console.ReadLine();
                pt.Stop();
                workerThread.Join();
            }
            catch (Exception e)
            {
                Console.WriteLine("`" + e.Message);
            }
            finally
            {
                q.Close();
            }
        }
        /// <summary>
        /// Returns token (requires user input)
        /// </summary>
        /// <returns></returns>
        public static AuthenticationResult GetToken(string authEndpoint, string tenant, string clientId)
        {
            var adalWinFormType = typeof(WebBrowserNavigateErrorEventArgs);
            Trace.WriteLine("Getting a random type from \'Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms\' to force it be deployed by mstest");

            AuthenticationResult result = null;
            var thread = new Thread(() =>
            {
                try
                {
                    var context = new AuthenticationContext(Path.Combine(authEndpoint, tenant));

                    result = context.AcquireToken(
                        resource: "https://management.core.windows.net/",
                        clientId: clientId,
                        redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"),
                        promptBehavior: PromptBehavior.Auto);
                }
                catch (Exception threadEx)
                {
                    Console.WriteLine(threadEx.Message);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();
            thread.Join();

            return result;

        }
Example #25
0
        public static void Main(string[] args)
        {
            // Create the thread object. This does not start the thread.
            Worker workerObject = new Worker();
            Thread workerThread = new Thread(workerObject.DoWork);

            // Start the worker thread.
            workerThread.Start();
            Console.WriteLine("main thread: Starting worker thread...");

            // Loop until worker thread activates.
            while (!workerThread.IsAlive);

            // Put the main thread to sleep for 1 millisecond to
            // allow the worker thread to do some work:
            Thread.Sleep(1);

            // Request that the worker thread stop itself:
            workerObject.RequestStop();

            // Use the Join method to block the current thread
            // until the object's thread terminates.
            workerThread.Join();
            Console.WriteLine("main thread: Worker thread has terminated.");
        }
Example #26
0
        public static string ShowFileDialogForExecutable(string fileName)
        {
            // Switch to default desktop
            if (SebWindowsClientMain.sessionCreateNewDesktop) SEBDesktopController.Show(SEBClientInfo.OriginalDesktop.DesktopName);

            // Create the thread object. This does not start the thread.
            Worker workerObject = new Worker();
            Thread workerThread = new Thread(workerObject.ShowFileDialogInThread);
            workerThread.SetApartmentState(ApartmentState.STA);
            workerObject.fileNameExecutable = fileName;

            // Start the worker thread.
            workerThread.Start();

            // Loop until worker thread activates.
            while (!workerThread.IsAlive) ;

            // Use the Join method to block the current thread
            // until the object's thread terminates.
            workerThread.Join();

            // Switch to new desktop
            if (SebWindowsClientMain.sessionCreateNewDesktop) SEBDesktopController.Show(SEBClientInfo.SEBNewlDesktop.DesktopName);

            return workerObject.fileNameFullPath;
        }
        private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
        {
            lastException = null;

            Thread thread = new Thread(
                delegate()
                    {
#if !DEBUG
                        try
                        {
#endif
                        userDelegate.Invoke();
#if !DEBUG
                        }
                        catch (Exception e)
                        {
                            lastException = e;
                        }
#endif
                    });
            thread.SetApartmentState(apartmentState);

            thread.Start();
            thread.Join();

            if (ExceptionWasThrown())
                ThrowExceptionPreservingStack(lastException);
        }
Example #28
0
 public void runAction(ActionSequence<NaoSkeleton> action)
 {
     Executor executor = new Executor(action, nao, FPS);
     Thread t = new Thread(new ThreadStart(executor.run));
     t.Start();
     t.Join();
 }
        public void IfResponseIsBlockedThenNextCommandWillWrite()
        {
            var b1 = new RedisInlineCommandBuilder();
            var b2 = new RedisInlineCommandBuilder();
            b1.SetCommand(":1");
            b2.SetCommand(":2");

            var loopbackConnection = new LoopbackConnection();
            var executor = new PipelinedCommandExecutor(loopbackConnection);

            var t1 = new Thread(() => executor.ExecuteCommand(b1));
            var t2 = new Thread(() => executor.ExecuteCommand(b2));

            t1.Start();
            t2.Start();

            Thread.Sleep(100);
            var str = Encoding.ASCII.GetString(loopbackConnection.GetBuffer());
            loopbackConnection.WriteResponce();

            t1.Join();
            t2.Join();

            executor.Dispose();

            Assert.That(str, Is.EqualTo(":1\r\n:2\r\n"));
        }
Example #30
0
        public void Should_be_able_to_block_calling_thread_until_collection_is_empty()
        {
            IPendingWorkCollection<int> pendingWorkCollection = CreatePendingWorkCollection();
            pendingWorkCollection.Send(1);
            pendingWorkCollection.Send(1);

            Assert.That(pendingWorkCollection.Count, Is.EqualTo(2));

            ThreadStart action = () => {
                Thread.Sleep(60);
                pendingWorkCollection.Retrieve(CancellationToken.None);
                Thread.Sleep(60);
            };

            Thread thread1 = new Thread(action);
            Thread thread2 = new Thread(action);

            thread1.Start();
            thread2.Start();

            pendingWorkCollection.Wait(CancellationToken.None);
            Assert.That(pendingWorkCollection.Count, Is.EqualTo(0));

            thread1.Join();
            thread2.Join();
        }