Esempio n. 1
14
        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();
            }
        }
 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;
 }
Esempio n. 3
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 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);
        }
Esempio n. 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");
        }
Esempio n. 6
0
 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;
 }
Esempio n. 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));
        }
Esempio n. 10
0
        /// <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;
        }
        /// <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;

        }
Esempio n. 12
0
        //------------------------------------------------------------------------------------------------------------------------
        public void Deinitialize()
        {
            lock (this)
            {
                try
                {
                    //close socket
#if NETFX
                    try { _sock?.Disconnect(false); } catch { }
                    try { _sock?.Close(); } catch { }
#endif
                    try { _sock?.Dispose(); } catch { }
                    _sock = null;

                    //stop tasks
                    IsRunning = false;
#if NETFX
                    DiscoveryTask?.Join(200);
                    BroadcastTask?.Join(200);
#elif UNIVERSAL
                    DiscoveryTask?.Wait(200);
                    BroadcastTask?.Wait(200);
#endif

                    DiscoveryTask = null;
                    BroadcastTask = null;
                }
                catch (Exception ex) { DebugEx.Assert(ex); }
            }
        }
Esempio n. 13
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();
        }
Esempio n. 14
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();

        }
Esempio n. 15
0
        public void Start()
        {
            try
            {
                var inputFileInfo = new FileInfo(_inputPath);
                using (var inputFileStream = inputFileInfo.OpenRead())
                {
                    _reader = CreateReader(inputFileStream);
                    _writer = new Thread(Write);
                    _writer.Start();
                    for (int i = 0; i < _threadsCount; i++)
                    {
                        var thread = new Thread(ReadAndProcess);
                        thread.Start();
                        _threads.Add(thread);
                    }

                    _threads?.ForEach(th => th.Join());
                    ReadFinish();
                    _writer?.Join();
                }
            }
            catch
            {
                new Thread(() => { _eventHandler.Invoke("Произошла ошибка при запуске процесса!"); }).Start();
            }
        }
Esempio n. 16
0
        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;
        }
        public void Stop()
        {
            _isCheckPortState = false;
            _portStateThread?.Join();

            Disconnect();
        }
Esempio n. 18
0
        public void Dispose()
        {
            Stop();
            _pollerThread?.Join();

            _client?.Dispose();
        }
Esempio n. 19
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            lock (_lock)
            {
                if (_isRunning)
                {
                    _refereceCount--;

                    if (_refereceCount == 0)
                    {
                        _isRunning = false;

                        _worker?.Join();

                        SDL_Quit();

                        OnJoyStickConnected    = null;
                        OnJoystickDisconnected = null;
                    }
                }
            }
        }
Esempio n. 20
0
        private void ThisWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _serialStop = true;
            _serialThread?.Join();

            Helpers.Serialize(_config, ConfigFile);
        }
Esempio n. 21
0
        public void Test_Transaction_ReleaseWhenFailToStart()
        {
            var blockingStream = new BlockingStream();
            var db             = new LiteDatabase(blockingStream)
            {
                Timeout = TimeSpan.FromSeconds(1)
            };
            Thread lockerThread = null;

            try
            {
                lockerThread = new Thread(() =>
                {
                    db.GetCollection <Person>().Insert(new Person());
                    blockingStream.ShouldBlock = true;
                    db.Checkpoint();
                    db.Dispose();
                });
                lockerThread.Start();
                blockingStream.Blocked.WaitOne(1000).Should().BeTrue();
                Assert.Throws <LiteException>(() => db.GetCollection <Person>().Insert(new Person())).Message.Should().Contain("timeout");
                Assert.Throws <LiteException>(() => db.GetCollection <Person>().Insert(new Person())).Message.Should().Contain("timeout");
            }
            finally
            {
                blockingStream.ShouldUnblock.Set();
                lockerThread?.Join();
            }
        }
Esempio n. 22
0
        private void Stop()
        {
            _cancellationTokenSource?.Cancel();

            _thread?.Join();
            _thread = null;
        }
 public void Dispose()
 {
     _runTransactions = false;
     _waitHandle.Set();
     _txMergingThread?.Join();
     _waitHandle.Dispose();
 }
Esempio n. 24
0
 public void Stop()
 {
     _clientCancelled = true;
     _clientThread?.Join();
     _clientThread = null;
     EventManager.Instance.onClientStopped.Invoke();
 }
Esempio n. 25
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();
            }
        }
Esempio n. 26
0
 public void Stop()
 {
     isRuning = false;
     thread?.Join();
     logRaderWriter?.Close();
     logTelWriter?.Close();
 }
        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"));
        }
Esempio n. 28
0
 public void Dispose()
 {
     _cancellationTokenSource?.Cancel();
     _cancellationTokenSource.Dispose();
     _readerThread?.Join();
     _udpClient?.Dispose();
 }
Esempio n. 29
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;
        }
Esempio n. 30
0
 /// <summary>
 /// Stops the accepting of new Connections.
 /// </summary>
 void StopListening()
 {
     tcpListener?.Stop();
     tcpListener = null;
     acceptConnectionsThread?.Join();
     acceptConnectionsThread = null;
 }
Esempio n. 31
0
 public void Close()
 {
     mThread?.Abort();
     mThread?.Join();
     mThread = null;
     System.Diagnostics.Debug.Assert(mSocketTarget == null);
 }
Esempio n. 32
0
        public void Stop()
        {
            var thread = _thread;

            if (thread == null)
            {
                return;
            }

            _thread = null;

            Thread alternateThread = null;

            if (_useAlternativeExchange)
            {
                alternateThread  = _alternateThread;
                _alternateThread = null;
            }

            _cancellationTokenSource?.Cancel();

            thread.Join();

            if (_useAlternativeExchange)
            {
                alternateThread?.Join();
            }

            _cancellationTokenSource?.Dispose();
        }
Esempio n. 33
0
        public void Dispose()
        {
            if (_connectionTimer != null)
            {
                _connectionTimer.Dispose();
                _connectionTimer = null;
            }

            _eventWait.Set();
            _requestHandlerThread?.Join();


            foreach (var ds in DataSources.Values)
            {
                ds.Disconnect();
            }

            /*
             * if (DataSources.ContainsKey("Interactive Brokers"))
             * {
             *  ((IB)DataSources["Interactive Brokers"]).Dispose();
             * }
             */
            if (DataSources.ContainsKey("ContinuousFuturesBroker"))
            {
                ((IContinuousFuturesBroker)DataSources["ContinuousFuturesBroker"]).Dispose();
            }
        }
Esempio n. 34
0
        public void Dispose()
        {
            if (_connectionTimer != null)
            {
                _connectionTimer.Dispose();
                _connectionTimer = null;
            }

            if (!_requestQueue.Reader.Completion.IsCompleted)
            {
                _requestQueue.Writer.Complete();
            }
            _requestHandlerThread?.Join();


            foreach (var ds in DataSources.Values)
            {
                ds.Disconnect();
            }

            /*
             * if (DataSources.ContainsKey("Interactive Brokers"))
             * {
             *  ((IB)DataSources["Interactive Brokers"]).Dispose();
             * }
             */
            if (DataSources.ContainsKey("ContinuousFuturesBroker"))
            {
                ((IContinuousFuturesBroker)DataSources["ContinuousFuturesBroker"]).Dispose();
            }
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            exit = true;
            componentsUpdater?.Join();
        }
Esempio n. 36
0
        public virtual void Dispose()
        {
            lock (_disposeLock)
            {
                if (_disposed)
                {
                    return;
                }

                _disposed = true;
            }

            _inactivityWatcherThread?.Join();
            _inactivityWatcherThread = null;

            DisposeOfManagedConnections();
            DeleteTemporaryDataArtifacts();
            var handlers = Disposed;

            try
            {
                handlers.Invoke(this, _autoDisposeInformation ??
                                new TempDbDisposedEventArgs(
                                    "TempDb instance was disposed",
                                    false,
                                    _timeout,
                                    _absoluteLifespan
                                    ));
            }
            catch
            {
                // suppress
            }
        }
Esempio n. 37
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();
            }
        }
Esempio n. 38
0
        protected override void Destroy()
        {
            commands.Enqueue(new SchedulerAsyncCommand(SchedulerAsyncCommandEnum.Dispose));

            workerThread?.Join();
            workerThread = null;
        }
Esempio n. 39
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;
 }
Esempio n. 40
0
        public void CacheMinimap(MapPreview preview)
        {
            bool launchPreviewLoaderThread;

            lock (syncRoot)
            {
                generateMinimap.Enqueue(preview);
                launchPreviewLoaderThread   = previewLoaderThreadShutDown;
                previewLoaderThreadShutDown = false;
            }

            if (launchPreviewLoaderThread)
            {
                Game.RunAfterTick(() =>
                {
                    // Wait for any existing thread to exit before starting a new one.
                    previewLoaderThread?.Join();

                    previewLoaderThread = new Thread(LoadAsyncInternal)
                    {
                        Name         = "Map Preview Loader",
                        IsBackground = true
                    };
                    previewLoaderThread.Start();
                });
            }
        }
Esempio n. 41
0
        private void btnStop_Click(object sender, EventArgs e)
        {
            _isEnd = true;

            progressBar.MarqueeAnimationSpeed = 0;

            cbYahoo.Enabled  = true;
            btnStop.Enabled  = false;
            btnPause.Enabled = false;

            checkerThread?.Abort();

            btnStop.Text = "Stopping...";
            stopwatch.Stop();
            timer.Stop();
            timer.Enabled = false;

            checkerThread?.Join();

            btnStart.Enabled   = true;
            btnAddMail.Enabled = true;
            btnDelete.Enabled  = true;
            tbMail.Enabled     = true;
            menuStrip.Enabled  = true;

            btnStop.Text = "Stop";

            if (mails.Count > 0)
            {
                btnExport.Enabled = true;
            }

            tbFind.Enabled = true;
        }
Esempio n. 42
0
        public void Dispose()
        {
            _runTransactions = false;

            // once all the concurrent transactions are done, this will signal the event, preventing
            // it from adding additional operations
            var done = _concurrentOperations.Signal();

            _waitHandle.Set();
            _txMergingThread?.Join();
            _waitHandle.Dispose();

            // make sure that the queue is empty and there are no pending
            // transactions waiting.
            // this is probably a bit more aggresive that what is needed, but it is better
            // to be cautious and slower on rare dispose than hang

            while (done == false)
            {
                try
                {
                    done = _concurrentOperations.Signal();
                }
                catch (InvalidOperationException)
                {
                    break;
                }
            }

            while (_operations.TryDequeue(out MergedTransactionCommand result))
            {
                result.TaskCompletionSource.TrySetCanceled();
            }
        }
        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);
        }
Esempio n. 44
0
        private void ReleaseResources(bool keepSounds)
        {
            for (int i = 0; i < playingChannels.Length; i++)
            {
                lock (playingChannels[i])
                {
                    for (int j = 0; j < playingChannels[i].Length; j++)
                    {
                        if (playingChannels[i][j] != null)
                        {
                            playingChannels[i][j].Dispose();
                        }
                    }
                }
            }

            streamingThread?.Join();
            for (int i = loadedSounds.Count - 1; i >= 0; i--)
            {
                if (keepSounds)
                {
                    loadedSounds[i].DeleteALBuffers();
                }
                else
                {
                    loadedSounds[i].Dispose();
                }
            }
            sourcePools[(int)SourcePoolIndex.Default]?.Dispose();
            sourcePools[(int)SourcePoolIndex.Voice]?.Dispose();

            SoundBuffers.ClearPool();
        }
Esempio n. 45
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();
        }
Esempio n. 46
0
 public override void Dispose()
 {
     Instance  = null;
     capturing = false;
     captureThread?.Join();
     captureThread = null;
 }
Esempio n. 47
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;
        }
Esempio n. 48
0
 public void StopWork()
 {
     IsWorking   = false;
     IsWorkPause = false;
     _workThread?.Join();
     _workThread = null;
 }
Esempio n. 49
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();
 }
        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;
        }
        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();
        }
        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);
        }
Esempio n. 53
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]);
            }
        }
Esempio n. 54
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.");
        }
Esempio n. 55
0
 private void OnDestroy()
 {
     connected = false;
     client?.Close();
     lookUpper?.Close();
     clientThread?.Join();
 }
Esempio n. 56
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);
        }
Esempio n. 57
0
        private void Cleanup()
        {
            isRunning = false;

            renderThread?.Join();

            tripleBuffer?.Dispose();

            stringFormat?.Dispose();
            fontCategoryNames?.Dispose();
            fontTeamNames?.Dispose();
            fontScores?.Dispose();
            penGridLines?.Dispose();
            brushTeamNames?.Dispose();
            brushScores?.Dispose();
            bitmapScores?.Dispose();

            if (brushesFireworks != null)
            {
                foreach (Brush brush in brushesFireworks)
                {
                    brush?.Dispose();
                }
            }
            if (brushesCategories != null)
            {
                foreach (Brush brush in brushesCategories)
                {
                    brush?.Dispose();
                }
            }
        }
Esempio n. 58
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();            
        }
Esempio n. 59
0
 public void Shutdown()
 {
     Initialized = false;
     udp?.Close();
     thread?.Join();
     thread?.Abort();
 }
Esempio n. 60
0
        public void Disconnect()
        {
            // only if started
            if (Connecting || Connected)
            {
                //destroy list.

                //Logger.Log("Disconnected");
                // close client
                client.Close();

                // wait until thread finished. this is the only way to guarantee
                // that we can call Connect() again immediately after Disconnect
                receiveThread?.Join();

                // clear send queues. no need to hold on to them.
                // (unlike receiveQueue, which is still needed to process the
                //  latest Disconnected message, etc.)
                sendQueue.Clear();

                // let go of this one completely. the thread ended, no one uses
                // it anymore and this way Connected is false again immediately.
                client = null;
            }
        }