Ejemplo n.º 1
0
 /// <summary>
 /// Releases resources used by the synchronized block.
 /// </summary>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && this.IsLockTaken)
     {
         SystemMonitor.Exit(this.SyncObject);
     }
 }
Ejemplo n.º 2
0
        public void TestMethod1()
        {
            var m = new Monitor(true);
            m.Start();

            Thread.Sleep(10*1000);
        }
Ejemplo n.º 3
0
 protected ViewerCache()
 {
     monitor = new Monitor();
     int cacheSize = (Console.WindowHeight - 15)/2;
     cache = new string[cacheSize + Math.Abs(cacheSize / 2)];
     reportCache = new string[cacheSize - Math.Abs(cacheSize / 2)];
     Updated = false;
     indexer = 0;
     reportIndexer = 0;
 }
Ejemplo n.º 4
0
        public void TestFieldWithSameNameAsVariable()
        {
            ExpressionContext context = new ExpressionContext(null, new Monitor());
            context.Variables.Add("doubleA", new ExpressionOwner());
            this.AssertCompileException("doubleA.doubleA", context);

            // But it should work for a public member
            context = new ExpressionContext();
            Monitor m = new Monitor();
            context.Variables.Add("I", m);

            var e = new DynamicExpression("i.i", ExpressionLanguage.Flee);
            Assert.AreEqual(m.I, (int)e.Invoke(context));
        }
Ejemplo n.º 5
0
        public static void Main()
        {
            NetworkLayer net = Singleton.Instance;
            if (net == null)
            {
                Debug.Print("Failed to initialize network layer");
                return;
            }

            Monitor monitor = new Monitor();

            NetworkTest test = new NetworkTest(net, monitor);
            test.Run(null);
        }
Ejemplo n.º 6
0
        public static void Run()
        {
            ManualResetEvent[] handles = new ManualResetEvent[mCount];
            Console.WriteLine("main thread id:{0}", Thread.CurrentThread.ManagedThreadId);

            for (int i = 0; i < mCount; i++)
            {
                handles[i] = new ManualResetEvent(false);
                Monitor monitor = new Monitor(handles[i]);
                ThreadPool.QueueUserWorkItem(monitor.Dispaly, new {num = 2});//parameter is a anonymous type
            }

            WaitHandle.WaitAll(handles);

            Console.WriteLine("completed.");
        }
Ejemplo n.º 7
0
        public void Invoke(Action action)
        {
            // Execute now if already on the thread
            if (Thread.CurrentThread == _thread)
            {
                action();
            }
            else
            {
                lock (action)
                {
                    // Schedule action
                    InvokeLater(action);

                    // Wait for action to complete
                    ThreadMonitor.Wait(action);
                }
            }
        }
Ejemplo n.º 8
0
        public void CancelTest() {

            var task = new Monitor();
            var count = 0;
            task.Execute(token => {              
                while (count != 100) {
                    count++;
                    token.ThrowIfCancellationRequested();
                    Thread.Sleep(100);
                }
            });

            Assert.True(task.IsRunning);

            task.Cancel();

            Assert.True(task.IsCanceled);
            Assert.False(task.IsRunning);

            Assert.AreNotEqual(100, count);
        }
Ejemplo n.º 9
0
        public void ProcessJobs()
        {
            if (Thread.CurrentThread != _thread)
            {
                throw new InvalidOperationException("Unable to process jobs on a different thread.");
            }

            lock (_queue)
            {
                // Process all jobs
                while (_queue.Count > 0)
                {
                    var action = _queue.Dequeue();

                    lock (action)
                    {
                        action(); //
                        ThreadMonitor.PulseAll(action);
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public void DefaultTest() {

            var messages = 0;
            var warnings = 0;
            var exceptions = 0;
            var task = new Monitor();

            task.Message += (sender, args) => {
                messages++;
            };
            task.Exception += (sender, args) => {
                exceptions++;
            };
            task.Warning += (sender, args) => {
                warnings++;
            };

            task.Execute(token => {
                task.OnMessage("m1");
                task.OnMessage("m2");
                task.OnMessage("m3");

                Thread.Sleep(200);

                task.OnWarning("w1");
                task.OnWarning("w2");

                task.OnException(new Exception());

            });

            Assert.AreEqual(true, task.IsRunning);
            task.Wait();

            Assert.AreEqual(3, messages);
            Assert.AreEqual(2, warnings);
            Assert.AreEqual(1, exceptions);
        }
Ejemplo n.º 11
0
        public void TestComplexMonitor()
        {
            this.Test(async() =>
            {
                object syncObject = new object();
                bool waiting      = false;
                List <string> log = new List <string>();
                Task t1           = Task.Run(() =>
                {
                    Monitor.Enter(syncObject);
                    log.Add("waiting");
                    waiting = true;
                    Monitor.Wait(syncObject);
                    log.Add("received pulse");
                    Monitor.Exit(syncObject);
                });

                Task t2 = Task.Run(async() =>
                {
                    while (!waiting)
                    {
                        await Task.Delay(1);
                    }

                    Monitor.Enter(syncObject);
                    Monitor.Pulse(syncObject);
                    log.Add("pulsed");
                    Monitor.Exit(syncObject);
                });

                await Task.WhenAll(t1, t2);

                string expected = "waiting, pulsed, received pulse";
                string actual   = string.Join(", ", log);
                Specification.Assert(expected == actual, "ControlledMonitor out of order, '{0}' instead of '{1}'", actual, expected);
            },
                      this.GetConfiguration());
        }
Ejemplo n.º 12
0
        /// <summary>Gets an enumerable of the tasks currently scheduled on this scheduler.</summary>
        /// <returns>An enumerable of the tasks currently scheduled.</returns>
        protected sealed override IEnumerable <Task> GetScheduledTasks()
        {
            bool lockTaken = false;

            try
            {
                Monitor.TryEnter(_tasks, ref lockTaken);
                if (lockTaken)
                {
                    return(_tasks);
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(_tasks);
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Notifies all waiting threads of a change in the object's state.
 /// </summary>
 public virtual void PulseAll() => SystemMonitor.PulseAll(this.SyncObject);
Ejemplo n.º 14
0
 /// <summary>
 /// Releases the lock on an object and blocks the current thread until it reacquires
 /// the lock.
 /// </summary>
 /// <returns>True if the call returned because the caller reacquired the lock for the specified
 /// object. This method does not return if the lock is not reacquired.</returns>
 public virtual bool Wait() => SystemMonitor.Wait(this.SyncObject);
Ejemplo n.º 15
0
        public void setMonitor(Monitor theMonitor)
        {
            GateInfoResponse gateInfoResponse = new GateInfoResponse();
            try {
                gateInfoResponse = server.getGateInfo(AppConfig.gateSensor, theMonitor.gateNo);
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            if (gateInfoResponse.error_code != 0)
            {
                MessageBox.Show("获取监控信息失败:" + gateInfoResponse.error_msg);
                toolStripStatusLabel.Text = "获取监控信息失败:" + gateInfoResponse.error_msg;
            }
            else
            {
                NVRDevice device = new NVRDevice();
                device.IP = gateInfoResponse.nvr_ip;
                device.password = gateInfoResponse.nvr_passwd;
                device.port = gateInfoResponse.nvr_port;
                device.username = gateInfoResponse.nvr_username;
                theMonitor.nvrDevice = device;
                theMonitor.channel = gateInfoResponse.nvr_channel;
                if (this.monitor != null)
                {
                    if (this.monitor.gateNo != theMonitor.gateNo)
                    {
                        toolStripStatusLabel.Text = "正在关闭现有视频!";
                        stopCurrentPreview();

                        if (this.monitor.nvrDevice != null && this.monitor.nvrDevice.IP != theMonitor.nvrDevice.IP)
                        {
                            //新监控和原监控的nvr不同,需要logout原nvr
                            toolStripStatusLabel.Text = "正在注销当前NVR!";
                            this.logout(this.monitor.nvrDevice);
                        }
                        toolStripStatusLabel.Text = "就绪!";
                    }
                    stop();
                }

                this.monitor = theMonitor;
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Enters the lock.
 /// </summary>
 /// <returns>The synchronized block.</returns>
 protected virtual SynchronizedBlock EnterLock()
 {
     SystemMonitor.Enter(this.SyncObject, ref this.IsLockTaken);
     return(this);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Notifies a thread in the waiting queue of a change in the locked object's state.
 /// </summary>
 internal virtual void Pulse() => SystemMonitor.Pulse(this.SyncObject);
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GISTrainer"/> class with a specified evaluation monitor.
 /// </summary>
 /// <param name="monitor">The evaluation monitor.</param>
 public GISTrainer(Monitor monitor)
     : this() {
     this.monitor = monitor;
 }
Ejemplo n.º 19
0
 public StylusAcquisition(PolhemusController controller, SingleShot singleShot, Monitor monitor = null)
 {
     if (controller == null) throw new ArgumentNullException("controller");
     if (singleShot == null) throw new ArgumentNullException("singleShot");
     _controller = controller;
     _singleShot = singleShot;
     _monitor = monitor;
     _continuousMode = false;
     initialization();
     if (monitor != null)
         ProgressChanged += new ProgressChangedEventHandler(sa_StylusProgressChanged);
 }
Ejemplo n.º 20
0
 //monitor only, independent of button state; stops on cancel only
 public StylusAcquisition(PolhemusController controller, Monitor monitor)
 {
     if (controller == null) throw new ArgumentNullException("controller");
     if (monitor == null) throw new ArgumentNullException("monitor");
     _controller = controller;
     _monitor = monitor;
     _continuousMode = true;
     initialization();
     ProgressChanged += new ProgressChangedEventHandler(sa_StylusProgressChanged);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Blocks the current thread until it can enter the <see cref="SemaphoreSlim"/>,
        /// using a 32-bit signed integer to measure the time interval,
        /// while observing a <see cref="T:System.Threading.CancellationToken"/>.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see cref="Timeout.Infinite"/>(-1) to
        /// wait indefinitely.</param>
        /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to observe.</param>
        /// <returns>true if the current thread successfully entered the <see cref="SemaphoreSlim"/>; otherwise, false.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a negative number other than -1,
        /// which represents an infinite time-out.</exception>
        /// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> was canceled.</exception>
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            CheckDispose();

            // Validate input
            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException(
                          "totalMilliSeconds", millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
            }

            cancellationToken.ThrowIfCancellationRequested();

            long startTimeTicks = 0;

            if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout > 0)
            {
                startTimeTicks = DateTime.UtcNow.Ticks;
            }

            bool lockTaken = false;

            //Register for cancellation outside of the main lock.
            //NOTE: Register/deregister inside the lock can deadlock as different lock acquisition orders could
            //      occur for (1)this.m_lockObj and (2)cts.internalLock
            CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.Register(s_cancellationTokenCanceledEventHandler, this);

            try
            {
                // Perf: first spin wait for the count to be positive, but only up to the first planned yield.
                //       This additional amount of spinwaiting in addition
                //       to Monitor2.Enter()’s spinwaiting has shown measurable perf gains in test scenarios.
                //
                SpinWait spin = new SpinWait();
                while (m_currentCount == 0 && !spin.NextSpinWillYield)
                {
                    spin.SpinOnce();
                }
                // entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot
                // clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters.
                try { }
                finally
                {
                    Monitor2.Enter(m_lockObj, ref lockTaken);
                    if (lockTaken)
                    {
                        m_waitCount++;
                    }
                }

                // If the count > 0 we are good to move on.
                // If not, then wait if we were given allowed some wait duration
                if (m_currentCount == 0)
                {
                    if (millisecondsTimeout == 0)
                    {
                        return(false);
                    }

                    // Prepare for the main wait...
                    // wait until the count become greater than zero or the timeout is expired
                    if (!WaitUntilCountOrTimeout(millisecondsTimeout, startTimeTicks, cancellationToken))
                    {
                        return(false);
                    }
                }

                // At this point the count should be greater than zero
                Contract.Assert(m_currentCount > 0);
                m_currentCount--;

                // Exposing wait handle which is lazily initialized if needed
                if (m_waitHandle != null && m_currentCount == 0)
                {
                    m_waitHandle.Reset();
                }
            }
            finally
            {
                // Release the lock
                if (lockTaken)
                {
                    m_waitCount--;
                    Monitor.Exit(m_lockObj);
                }

                // Unregister the cancellation callback.
                cancellationTokenRegistration.Dispose();
            }

            return(true);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Releases the lock on an object and blocks the current thread until it reacquires
 /// the lock.
 /// </summary>
 /// <returns>True if the call returned because the caller reacquired the lock for the specified
 /// object. This method does not return if the lock is not reacquired.</returns>
 internal virtual bool Wait() => SystemMonitor.Wait(this.SyncObject);
Ejemplo n.º 23
0
        public static event EventHandler GatewayCacheUpdated = null;    //Notify the UI to pull the latest data update
		
		//Interface
        static ActiveGateway() {
            _Data = new DataSet();
            _Monitor = new Monitor(7500);
            _Monitor.DataUpdate += new DataEventHandler(OnDataUpdate);
        }
Ejemplo n.º 24
0
 protected Parking()
 {
     monitor = new Monitor();
     reservations = new List<ParkingReservation>();
     open = true;
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Releases the lock on an object and blocks the current thread until it reacquires
 /// the lock. If the specified time-out interval elapses, the thread enters the ready
 /// queue.
 /// </summary>
 /// <param name="millisecondsTimeout">The number of milliseconds to wait before the thread enters the ready queue.</param>
 /// <returns>True if the lock was reacquired before the specified time elapsed; false if the
 /// lock was reacquired after the specified time elapsed. The method does not return
 /// until the lock is reacquired.</returns>
 public virtual bool Wait(int millisecondsTimeout) => SystemMonitor.Wait(this.SyncObject, millisecondsTimeout);
Ejemplo n.º 26
0
 /// <summary>
 /// Releases the lock on an object and blocks the current thread until it reacquires
 /// the lock. If the specified time-out interval elapses, the thread enters the ready
 /// queue.
 /// </summary>
 /// <param name="timeout">A System.TimeSpan representing the amount of time to wait before the thread enters
 /// the ready queue.</param>
 /// <returns>True if the lock was reacquired before the specified time elapsed; false if the
 /// lock was reacquired after the specified time elapsed. The method does not return
 /// until the lock is reacquired.</returns>
 public virtual bool Wait(TimeSpan timeout) => SystemMonitor.Wait(this.SyncObject, timeout);
Ejemplo n.º 27
0
        /// <summary>
        /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
        /// 32-bit signed integer to measure the time interval, while observing a <see
        /// cref="T:System.Threading.CancellationToken"/>.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
        /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
        /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
        /// observe.</param>
        /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
        /// false.</returns>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
        /// negative number other than -1, which represents an infinite time-out.</exception>
        /// <exception cref="T:System.InvalidOperationException">
        /// The maximum number of waiters has been exceeded.
        /// </exception>
        /// <exception cref="T:System.Threading.OperationCanceledException"><paramref
        /// name="cancellationToken"/> was canceled.</exception>
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            cancellationToken.ThrowIfCancellationRequested(); // an early convenience check

            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
            }

            if (!IsSet)
            {
                if (millisecondsTimeout == 0)
                {
                    // For 0-timeouts, we just return immediately.
                    return(false);
                }


                // We spin briefly before falling back to allocating and/or waiting on a true event.
                uint startTime = 0;
                bool bNeedTimeoutAdjustment  = false;
                int  realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.

                if (millisecondsTimeout != Timeout.Infinite)
                {
                    // We will account for time spent spinning, so that we can decrement it from our
                    // timeout.  In most cases the time spent in this section will be negligible.  But
                    // we can't discount the possibility of our thread being switched out for a lengthy
                    // period of time.  The timeout adjustments only take effect when and if we actually
                    // decide to block in the kernel below.

                    startTime = TimeoutHelper.GetTime();
                    bNeedTimeoutAdjustment = true;
                }

                // Spin
                int spinCount = SpinCount;
                var spinner   = new SpinWait();
                while (spinner.Count < spinCount)
                {
                    spinner.SpinOnce(SpinWait.Sleep1ThresholdForLongSpinBeforeWait);

                    if (IsSet)
                    {
                        return(true);
                    }

                    if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                    }
                }

                // Now enter the lock and wait.
                EnsureLockObjectCreated();

                // We must register and unregister the token outside of the lock, to avoid deadlocks.
                using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this))
                {
                    lock (m_lock)
                    {
                        // Loop to cope with spurious wakeups from other waits being canceled
                        while (!IsSet)
                        {
                            // If our token was canceled, we must throw and exit.
                            cancellationToken.ThrowIfCancellationRequested();

                            //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
                            if (bNeedTimeoutAdjustment)
                            {
                                realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
                                if (realMillisecondsTimeout <= 0)
                                {
                                    return(false);
                                }
                            }

                            // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock,
                            // so after updating waiters, we must check IsSet again.
                            // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
                            // read from IsSet.  This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
                            // operation which provides a full memory barrier.
                            // If we see IsSet=false, then we are guaranteed that Set() will see that we are
                            // waiting and will pulse the monitor correctly.

                            Waiters = Waiters + 1;

                            if (IsSet)     //This check must occur after updating Waiters.
                            {
                                Waiters--; //revert the increment.
                                return(true);
                            }

                            // Now finally perform the wait.
                            try
                            {
                                // ** the actual wait **
                                if (!Monitor.Wait(m_lock, realMillisecondsTimeout))
                                {
                                    return(false); //return immediately if the timeout has expired.
                                }
                            }
                            finally
                            {
                                // Clean up: we're done waiting.
                                Waiters = Waiters - 1;
                            }
                            // Now just loop back around, and the right thing will happen.  Either:
                            //     1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
                            // or  2. the wait was successful. (the loop will break)
                        }
                    }
                }
            } // automatically disposes (and unregisters) the callback

            return(true); //done. The wait was satisfied.
        }