public bool Wait(TimeSpan timeout)
 {
     SpinWait s = new SpinWait();
     bool waitResult = true;
     while (m_state == 0)
     {
         if (s.Spin() >= s_spinCount)
         {
             if (m_eventObj == null)
             {
                 ManualResetEvent newEvent =
                     new ManualResetEvent(m_state == 1);
                 if (Interlocked.CompareExchange<EventWaitHandle>(
                         ref m_eventObj, newEvent, null) == null)
                 {
                     // If someone set the flag before seeing the new
                     // event obj, we must ensure it’s been set.
                     if (m_state == 1)
                         m_eventObj.Set();
                 }
                 else
                 {
                     // Lost the race w/ another thread. Just use
                     // its event.
                     newEvent.Close();
                 }
             }
             waitResult = m_eventObj.WaitOne(timeout);
         }
     }
     return waitResult;
 }
示例#2
0
        public static void Run()
        {
            var queue = new ConcurrentQueue<int>();

            // begin
            var producer = Task.Run(() =>
            {
                foreach (var value in Enumerable.Range(1, 10000))
                {
                    queue.Enqueue(value);
                }
            });

            var consumer = Task.Run(() =>
            {
                var spinWait = new SpinWait();
                var value = 0;
                while (value != 10000)
                {
                    if (!queue.TryDequeue(out value))
                    {
                        spinWait.SpinOnce();
                        continue;
                    }
                    Logger.Log("Value: {0}", value);
                }
            });

            Task.WaitAll(producer, consumer);
            // end
        }
 public void Clear()
 {
     lock (clearLock)
     {
         isSend = false;
         if (sendDataQueue.Count > 0)
         {
             SendData cmd;
             if (!sendDataQueue.TryDequeue(out cmd))
             {
                 SpinWait spinWait = new SpinWait();
                 while (sendDataQueue.TryDequeue(out cmd))
                 {
                     spinWait.SpinOnce();
                 }
             }
         }
         if (InterimPacketBuffer != null)
         {
             Session.Pool.FixedBufferPool.Push(InterimPacketBuffer);
             InterimPacketBuffer = null;
         }
         while (ReceiveBuffers.Count > 0)
         {
             var packetBuffer = ReceiveBuffers.Dequeue();
             Session.Pool.FixedBufferPool.Push(packetBuffer);
         }
     }
     SendBuffer.Clear();
     NoComplateCmd = null;
     alreadyReceivePacketLength = 0;
     needReceivePacketLenght = 0;
 }
示例#4
0
        public static void RunSpinWaitTests()
        {
            SpinWait spinner = new SpinWait();

            spinner.SpinOnce();
            Assert.Equal(spinner.Count, 1);
        }
    public void Enter() {
        // If calling thread already owns the lock, increment recursion count and return
        Int32 threadId = Thread.CurrentThread.ManagedThreadId;
        if (threadId == m_owningThreadId) { m_recursion++; return; }

        // The calling thread doesn't own the lock, try to get it
        SpinWait spinwait = new SpinWait();
        for (Int32 spinCount = 0; spinCount < m_spincount; spinCount++) {
            // If the lock was free, this thread got it; set some state and return
            if (Interlocked.CompareExchange(ref m_waiters, 1, 0) == 0) goto GotLock;

            // Black magic: give other threads a chance to run
            // in hopes that the lock will be released
            spinwait.SpinOnce();
        }

        // Spinning is over and the lock was still not obtained, try one more time
        if (Interlocked.Increment(ref m_waiters) > 1) {
            // Still contention, this thread must wait
            m_waiterLock.WaitOne(); // Wait for the lock; performance hit
            // When this thread wakes, it owns the lock; set some state and return
        }

        GotLock:
        // When a thread gets the lock, we record its ID and
        // indicate that the thread owns the lock once
        m_owningThreadId = threadId; m_recursion = 1;
    }
示例#6
0
文件: StLock.cs 项目: duarten/mono
		internal bool SlowEnter (StCancelArgs cargs)
		{
			int lastTime = (cargs.Timeout != Timeout.Infinite) ? Environment.TickCount : 0;
			StWaitBlock wb = null;
			do {
				int sc = spinCount;
#if NET_4_0
				var spinWait = new SpinWait ();
#endif
				do {
					if (state == FREE &&
					    Interlocked.CompareExchange (ref state, BUSY, FREE) == FREE) {
						return true;
					}
					if (top != null || sc-- <= 0) {
						break;
					}
#if NET_4_0
					spinWait.SpinOnce ();
#else
					Thread.SpinWait (1);
#endif
				} while (true);


				if (wb == null) {
					wb = new StWaitBlock (1);
				} else {
					wb.parker.Reset ();
				}

				do {
					StWaitBlock t;
					wb.next = t = top;
					if (Interlocked.CompareExchange (ref top, wb, t) == t) {
						break;
					}
				} while (true);

				if (TryEnter ()) {
					wb.parker.SelfCancel ();
					return true;
				}

				int ws = wb.parker.Park (cargs);

				if (ws != StParkStatus.Success) {
					cargs.ThrowIfException (ws);
					return false;
				}

				if (TryEnter ()) {
					return true;
				}
				
				if (!cargs.AdjustTimeout (ref lastTime)) {
					return false;
				}
			} while (true);
		}
		public void ParticipateUntil (Func<bool> predicate)
		{
			SpinWait sw = new SpinWait ();
			
			while (!predicate ())
				sw.SpinOnce ();
		}
示例#8
0
 public PowerRegulator()
 {
     _Sample = 1.0f;
     _SpinWait = new SpinWait();
     _SpinCount = 0;
     _WorkCount = 0;
     _Busy = 0;
     _TimeCount = new TimeCounter();
     _FPS = new FPSCounter();
 }
		public void ParallelForTestCase ()
		{
			ParallelTestHelper.Repeat (() => {
				int[] expected = Enumerable.Range (1, 1000).Select ((e) => e * 2).ToArray ();
				int[] actual = Enumerable.Range (1, 1000).ToArray ();
				SpinWait sw = new SpinWait ();
				
				Parallel.For (0, actual.Length, (i) => { actual[i] *= 2; sw.SpinOnce (); });
				
				CollectionAssert.AreEquivalent (expected, actual, "#1, same");
				CollectionAssert.AreEqual (expected, actual, "#2, in order");
			});
		}
示例#10
0
文件: SpinWait.cs 项目: Indifer/Test
		public static bool SpinUntil (Func<bool> condition, int millisecondsTimeout)
		{
			SpinWait sw = new SpinWait ();
			Watch watch = Watch.StartNew ();

			while (!condition ()) {
				if (watch.ElapsedMilliseconds > millisecondsTimeout)
					return false;
				sw.SpinOnce ();
			}

			return true;
		}
示例#11
0
        private void run(CancellationToken token)
        {
            var list = new List<Entry>(_maxBatchSize);
            Logger.Info("[StorageWriter] Entering main loop. {0}", _maxBatchSize);

            var spinWait = new SpinWait();
            while (token.IsCancellationRequested == false)
            {
                try
                {
                    while (list.Count < _maxBatchSize)
                    {

                        Entry entry;
                        if (_queue.TryDequeue(out entry) == false)
                        {
                            break;
                        }

                        Logger.Debug("[StorageWriter] Got something to write...");

                        if (entry.ShouldDrop())
                        {
                            Logger.Debug("[StorageWriter] Dropping message....too old.");
                            entry.Harikiri();
                        }
                        else
                            list.Add(entry);
                    }

                    if (list.Count > 0)
                    {
                        store(list.ToArray());
                        list.Clear();
                    }
                    else
                    {
                        spinWait.SpinOnce();
                    }
                }
                catch (Exception e)
                {
                    Logger.Warn("[StorageWriter] Error in mainloop.", e);
                }

                _spinwait.SpinOnce();
            }

            Logger.Info("[StorageWriter] Exiting. No more spinning for me today...");
        }
示例#12
0
		public void EnterReadLock()
		{
			SpinWait sw = new SpinWait();
			do
			{
				while ((rwlock & (RwWrite | RwWait)) > 0)
					sw.SpinOnce();

				if ((Interlocked.Add(ref rwlock, RwRead) & (RwWait | RwWait)) == 0)
					return;

				Interlocked.Add(ref rwlock, -RwRead);
			} while (true);
		}
示例#13
0
 /// <summary>
 /// 循环工作
 /// </summary>
 private static void LoopWork()
 {
     var spinWait = new SpinWait();
     while (true)
     {
         lock (syncRoot)
         {
             foreach (var item in actions)
             {
                 item.Invoke();
             }
         }
         spinWait.SpinOnce();
     }
 }
示例#14
0
文件: SpinWait.cs 项目: g992com/esb
 /// <summary>在指定条件得到满足或指定超时过期之前自旋。</summary>
 /// <returns>如果条件在超时时间内得到满足,则为 true;否则为 false</returns>
 /// <param name="condition">在返回 true 之前重复执行的委托。</param>
 /// <param name="millisecondsTimeout">等待的毫秒数,或为 <see cref="F:System.Threading.Timeout.Infinite" /> (-1),表示无限期等待。</param>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="condition" /> 参数为 null。</exception>
 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout" /> 是一个非 -1 的负数,而 -1 表示无限期超时。</exception>
 public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout)
 {
     if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException("millisecondsTimeout");
     if (condition == null) throw new ArgumentNullException("condition");
     long ticks = 0;
     if (millisecondsTimeout != 0 && millisecondsTimeout != -1) ticks = DateTime.UtcNow.Ticks;
     SpinWait wait = new SpinWait();
     while (!condition())
     {
         if (millisecondsTimeout == 0) return false;
         wait.SpinOnce();
         if (millisecondsTimeout != -1 && wait.NextSpinWillYield && millisecondsTimeout <= (DateTime.UtcNow.Ticks - ticks) / 10000) return false;
     }
     return true;
 }
示例#15
0
        public override Event Dequeue()
        {
            Event result = null;
            SpinWait spinWait = new SpinWait();

            while (!closing)
            {
                if (queue.TryDequeue(out result))
                {
                    break;
                }
                spinWait.SpinOnce();
            }

            return result;
        }
示例#16
0
文件: ZmqUtil.cs 项目: MarouenK/Zebus
        public static int SendWithTimeout(this ZmqSocket socket, byte[] buffer, int length, TimeSpan timeout)
        {
            var stopwatch = Stopwatch.StartNew();
            var spinWait = new SpinWait();
            int result;
            do
            {
                result = socket.Send(buffer, length, SocketFlags.DontWait);
                if (socket.SendStatus != SendStatus.TryAgain)
                    break;

                spinWait.SpinOnce();
            }
            while (stopwatch.Elapsed <= timeout);

            return result;
        }
示例#17
0
 public static bool SpinWaitForCondition(Func<bool> predicate, int timeout)
 {
     Thread.MemoryBarrier();
     var sw = new Stopwatch();
     var spin = new SpinWait();
     sw.Start();
     while (sw.ElapsedMilliseconds < timeout)
     {
         if (predicate())
         {
             sw.Stop();
             return true;
         }
         spin.SpinOnce();
     }
     sw.Stop();
     return false;
 }
        protected override void ConsumeItems( int count )
        {
            SpinWait spinWait = new SpinWait();
            int value;

            for ( int i = 0; i < count; )
            {
                if ( this.queue.TryDequeue( out value ) )
                {
                    i++;

                    spinWait.Reset();
                }
                else
                {
                    spinWait.SpinOnce();
                }
            }
        }
示例#19
0
		public void EnterWriteLock()
		{
			SpinWait sw = new SpinWait();
			do
			{
				int state = rwlock;
				if (state < RwWrite)
				{
					if (Interlocked.CompareExchange(ref rwlock, RwWrite, state) == state)
						return;
					state = rwlock;
				}
				// We register our interest in taking the Write lock (if upgradeable it's already done)
				while ((state & RwWait) == 0 && Interlocked.CompareExchange(ref rwlock, state | RwWait, state) != state)
					state = rwlock;
				// Before falling to sleep
				while (rwlock > RwWait)
					sw.SpinOnce();
			} while (true);
		}
示例#20
0
		public void EnterReadLock (ref bool taken)
		{
			if (taken)
				throw new ArgumentException ("taken", "taken needs to be set to false");

			SpinWait sw = new SpinWait ();
			bool cont = true;

			do {
				while ((rwlock & (RwWrite | RwWait)) > 0)
					sw.SpinOnce ();

				try {}
				finally {
					if ((Interlocked.Add (ref rwlock, RwRead) & (RwWait | RwWait)) == 0) {
						taken = true;
						cont = false;
					} else {
						Interlocked.Add (ref rwlock, -RwRead);
					}
				}
			} while (cont);
		}
        private void ProcessQueue()
        {
            // We cannot do a CAS and exit the method is this.currentThread is not null, because this field is set
            // after the this.workItemsCount field is decremented. Field this.workItemsCount, and not this.currentThread,
            // guarantees there is a single running thread.
            this.currentThread = Thread.CurrentThread;

            // Set the SynchronizationContext to ensure await goes back to the right context.
            SynchronizationContext oldSynchronizationContext = SynchronizationContext.Current;
            SynchronizationContext.SetSynchronizationContext( this.SynchronizationContext );

            try
            {
                SpinWait spinWait = new SpinWait();
                do
                {
                    IAction action;
                    while ( !this.workItems.TryDequeue( out action ) )
                    {
                        spinWait.SpinOnce();
                    }

                    // TODO: Cooperative multitasking: Avoid processing the whole queue if it's very long.
                    // Rather interrupt and requeue a ProcessQueue task. Use Stopwatch

                    action.Invoke();

            #pragma warning disable 420
                } while ( Interlocked.Decrement( ref this.workItemsCount ) > 0 );
            #pragma warning restore 420
            }
            finally
            {
                this.currentThread = null;
                SynchronizationContext.SetSynchronizationContext( oldSynchronizationContext );
            }
        }
        // Helper method to avoid repeating Break() logic between ParallelState64 and ParallelState64<TLocal>
        internal static void Break(long iteration, ParallelLoopStateFlags64 pflags)
        {
            int oldValue = ParallelLoopStateFlags.PLS_NONE;

            // Attempt to change state from "not stopped or broken or canceled or exceptional" to "broken".
            if (!pflags.AtomicLoopStateUpdate(ParallelLoopStateFlags.PLS_BROKEN,
                                             ParallelLoopStateFlags.PLS_STOPPED | ParallelLoopStateFlags.PLS_EXCEPTIONAL | ParallelLoopStateFlags.PLS_CANCELED,
                                             ref oldValue))
            {

                // If we were already stopped, we have a problem
                if ((oldValue & ParallelLoopStateFlags.PLS_STOPPED) != 0)
                {
                    throw new InvalidOperationException(
                        Environment.GetResourceString("ParallelState_Break_InvalidOperationException_BreakAfterStop"));
                }
                else
                {
                    // Apparently we previously got cancelled or became exceptional. No action necessary
                    return;
                }
            }

            // replace shared LowestBreakIteration with CurrentIteration, but only if CurrentIteration
            // is less than LowestBreakIteration.
            long oldLBI = pflags.LowestBreakIteration;
            if (iteration < oldLBI)
            {
                SpinWait wait = new SpinWait();
                while (Interlocked.CompareExchange(
                    ref pflags.m_lowestBreakIteration,
                        iteration,
                        oldLBI) != oldLBI)
                {
                    wait.SpinOnce();
                    oldLBI = pflags.LowestBreakIteration;
                    if (iteration > oldLBI) break;
                }
            }

        }
示例#23
0
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) {
            if (millisecondsTimeout < -1)
                throw new ArgumentOutOfRangeException("millisecondsTimeout");

            ThrowIfDisposed();

            if (!IsSet) {
                var wait = new SpinWait();

                while (!IsSet) {
                    if (wait.Count < spinCount) {
                        wait.SpinOnce();
                        continue;
                    }

                    break;
                }

                cancellationToken.ThrowIfCancellationRequested();

                if (IsSet)
                    return true;

                WaitHandle handle = WaitHandle;

                if (cancellationToken.CanBeCanceled) {
                    int result = WaitHandle.WaitAny(new[] {handle, cancellationToken.WaitHandle}, millisecondsTimeout, false);
                    if (result == 1)
                        throw new OperationCanceledException(cancellationToken.ToString());
                    if (result == WaitHandle.WaitTimeout)
                        return false;
                } else {
                    if (!handle.WaitOne(millisecondsTimeout, false))
                        return false;
                }
            }

            return true;
        }
        public async Task can_backup_to_directory_multiple_backups_with_long_interval()
        {
            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore())
            {
                var periodicBackupRunner = (await GetDocumentDatabaseInstanceFor(store)).PeriodicBackupRunner;

                // get by reflection the maxTimerTimeoutInMilliseconds field
                // this field is the maximum interval acceptable in .Net's threading timer
                // if the requested backup interval is bigger than this maximum interval,
                // a timer with maximum interval will be used several times until the interval cumulatively
                // will be equal to requested interval
                typeof(PeriodicBackupRunner)
                .GetField(nameof(PeriodicBackupRunner.MaxTimerTimeout), BindingFlags.Instance | BindingFlags.Public)
                .SetValue(periodicBackupRunner, TimeSpan.FromMilliseconds(100));

                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new User { Name = "oren" }, "users/1");

                    await session.SaveChangesAsync();
                }

                var config = new PeriodicBackupConfiguration
                {
                    LocalSettings = new LocalSettings
                    {
                        FolderPath = backupPath
                    },
                    IncrementalBackupFrequency = "* * * * *" //every minute
                };

                var backupTaskId = (await store.Maintenance.SendAsync(new UpdatePeriodicBackupOperation(config))).TaskId;
                await store.Maintenance.SendAsync(new StartBackupOperation(true, backupTaskId));

                var operation = new GetPeriodicBackupStatusOperation(backupTaskId);
                SpinWait.SpinUntil(() =>
                {
                    var getPeriodicBackupResult = store.Maintenance.Send(operation);
                    return(getPeriodicBackupResult.Status?.LastEtag > 0);
                }, TimeSpan.FromSeconds(15));

                var etagForBackups = store.Maintenance.Send(operation).Status.LastEtag;
                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new User { Name = "ayende" }, "users/2");

                    await session.SaveChangesAsync();
                }

                await store.Maintenance.SendAsync(new StartBackupOperation(false, backupTaskId));

                SpinWait.SpinUntil(() =>
                {
                    var newLastEtag = store.Maintenance.Send(operation).Status.LastEtag;
                    return(newLastEtag != etagForBackups);
                }, TimeSpan.FromSeconds(15));
            }

            using (var store = GetDocumentStore(new Options
            {
                ModifyDatabaseName = s => $"{s}_2"
            }))
            {
                await store.Smuggler.ImportIncrementalAsync(new DatabaseSmugglerImportOptions(),
                                                            Directory.GetDirectories(backupPath).First());

                using (var session = store.OpenAsyncSession())
                {
                    var users = await session.LoadAsync <User>(new[] { "users/1", "users/2" });

                    Assert.True(users.Any(x => x.Value.Name == "oren"));
                    Assert.True(users.Any(x => x.Value.Name == "ayende"));
                }
            }
        }
        /// <summary>
        /// Processes all synchronous events that must take place before the next time loop for the algorithm
        /// </summary>
        public virtual void ProcessSynchronousEvents()
        {
            // how to do synchronous market orders for real brokerages?

            // in backtesting we need to wait for orders to be removed from the queue and finished processing
            if (!_algorithm.LiveMode)
            {
                var spinWait = new SpinWait();
                while (!_orderRequestQueue.IsEmpty)
                {
                    // spin wait until the queue is empty
                    spinWait.SpinOnce();
                }
                // now wait for completed processing to signal
                _processingCompletedEvent.Wait();
                return;
            }

            Log.Debug("BrokerageTransactionHandler.ProcessSynchronousEvents(): Enter");

            // every morning flip this switch back
            if (_syncedLiveBrokerageCashToday && DateTime.Now.Date != LastSyncDate)
            {
                _syncedLiveBrokerageCashToday = false;
            }

            // we want to sync up our cash balance before market open
            if (_algorithm.LiveMode && !_syncedLiveBrokerageCashToday && DateTime.Now.TimeOfDay >= _liveBrokerageCashSyncTime)
            {
                try
                {
                    // only perform cash syncs if we haven't had a fill for at least 10 seconds
                    if (TimeSinceLastFill > TimeSpan.FromSeconds(10))
                    {
                        PerformCashSync();
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Updating cash balances");
                }
            }

            // we want to remove orders older than 10k records, but only in live mode
            const int maxOrdersToKeep = 10000;
            if (_orders.Count < maxOrdersToKeep + 1)
            {
                Log.Debug("BrokerageTransactionHandler.ProcessSynchronousEvents(): Exit");
                return;
            }

            int max = _orders.Max(x => x.Key);
            int lowestOrderIdToKeep = max - maxOrdersToKeep;
            foreach (var item in _orders.Where(x => x.Key <= lowestOrderIdToKeep))
            {
                Order value;
                OrderTicket ticket;
                _orders.TryRemove(item.Key, out value);
                _orderTickets.TryRemove(item.Key, out ticket);
            }

            Log.Debug("BrokerageTransactionHandler.ProcessSynchronousEvents(): Exit");
        }
        public async Task PushServiceBadAetTest()
        {
            var testAETConfigModel = GetTestAETConfigModel();
            var destination        = testAETConfigModel.AETConfig.Destination;

            var tempFolder = CreateTemporaryDirectory();

            // Grab a structure set file
            var file = new FileInfo(@"Images\LargeSeriesWithContour\rtstruct.dcm");

            file.CopyTo(Path.Combine(tempFolder.FullName, file.Name));

            var resultDirectory = CreateTemporaryDirectory();

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, destination.Port);

                var dataSender = new DicomDataSender();
                var echoResult = await dataSender.DicomEchoAsync(
                    "RListener",
                    destination.Title,
                    destination.Port,
                    destination.Ip);

                // Check echo
                Assert.IsTrue(echoResult == DicomOperationResult.Success);

                using (var deleteService = CreateDeleteService())
                    using (var pushService = CreatePushService())
                        using (var pushQueue = pushService.PushQueue)
                        {
                            deleteService.Start();
                            pushService.Start();

                            TransactionalEnqueue(
                                pushQueue,
                                new PushQueueItem(
                                    destinationApplicationEntity: new GatewayApplicationEntity("", -1, "ababa"),
                                    calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                    callingApplicationEntityTitle: testAETConfigModel.CallingAET,
                                    associationGuid: Guid.NewGuid(),
                                    associationDateTime: DateTime.UtcNow,
                                    filePaths: tempFolder.GetFiles().Select(x => x.FullName).ToArray()));

                            // Wait for all events to finish on the data received
                            SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

                            SpinWait.SpinUntil(() => new DirectoryInfo(tempFolder.FullName).Exists == false, TimeSpan.FromSeconds(30));

                            Assert.IsFalse(new DirectoryInfo(tempFolder.FullName).Exists);
                        }
            }
        }
        internal void RemoveCallback(CancellationTokenRegistration tokenReg)
        {
            if (!canceled) {
                lock (syncRoot) {
                    if (!canceled) {
                        callbacks.Remove (tokenReg);
                        return;
                    }
                }
            }

            SpinWait sw = new SpinWait ();
            while (!processed)
                sw.SpinOnce ();
        }
示例#28
0
        public async Task DoesReadBalancerAndMaxNumberOfRequestsClietnConfigurationTakeEffectOnCurrentRequestExecutor()
        {
            var nodesCount = 3;
            var db         = GetDatabaseName();

            var leader = await CreateRaftClusterAndGetLeader(nodesCount);

            var result = await CreateDatabaseInCluster(db, nodesCount, leader.WebUrl);

            using (var store =
                       new DocumentStore
            {
                Urls = new[] { leader.WebUrl },
                Database = db,
                Conventions = new Raven.Client.Documents.Conventions.DocumentConventions
                {
                    ReadBalanceBehavior = Raven.Client.Http.ReadBalanceBehavior.RoundRobin,
                    MaxNumberOfRequestsPerSession = 5
                }
            }.Initialize())
            {
                SpinWait.SpinUntil(() =>
                {
                    using (leader.ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext ctx))
                        using (ctx.OpenReadTransaction())
                        {
                            var record = leader.ServerStore.Cluster.ReadDatabase(ctx, db);
                            return(record.Topology.Members.Count == nodesCount);
                        }
                }, TimeSpan.FromSeconds(10));

                using (var session = store.OpenSession())
                {
                    session.Store(new User
                    {
                        Name = "Samson"
                    });
                    session.SaveChanges();
                }

                await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                {
                    using (var session = store.OpenAsyncSession())
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            await session.StoreAsync(new User
                            {
                                Name = "Samson"
                            });
                            await session.SaveChangesAsync();
                        }
                    }
                });

                HashSet <string> usedUrls = new HashSet <string>();
                for (var i = 0; i < nodesCount; i++)
                {
                    using (var session = store.OpenSession())
                    {
                        Raven.Client.Http.ServerNode serverNode = await session.Advanced.GetCurrentSessionNode();

                        Assert.True(usedUrls.Add(serverNode.Url.ToLower()));
                    }
                }
                Assert.Equal(nodesCount, usedUrls.Count);


                // now, we modify the values and make sure that we received them
                store.Maintenance.Server.Send(
                    new PutServerWideClientConfigurationOperation(
#pragma warning disable 618
                        new ClientConfiguration {
                    MaxNumberOfRequestsPerSession = 10, PrettifyGeneratedLinqExpressions = false, ReadBalanceBehavior = Raven.Client.Http.ReadBalanceBehavior.None
                }));
#pragma warning restore 618


                Assert.True(SpinWait.SpinUntil(() =>
                {
                    using (var session = store.OpenSession())
                    {
                        session.Load <User>("users/1"); // we need this to "pull" the new config
                        return(session.Advanced.RequestExecutor.Conventions.MaxNumberOfRequestsPerSession == 10);
                    }
                }, TimeSpan.FromSeconds(10)));



                using (var session = store.OpenAsyncSession())
                {
                    for (int i = 0; i < 6; i++)
                    {
                        await session.StoreAsync(new User
                        {
                            Name = "Samson"
                        });

                        await session.SaveChangesAsync();
                    }
                }

                usedUrls.Clear();
                for (var i = 0; i < nodesCount; i++)
                {
                    using (var session = store.OpenSession())
                    {
                        Raven.Client.Http.ServerNode serverNode1 = await session.Advanced.GetCurrentSessionNode();

                        usedUrls.Add(serverNode1.Url.ToLower());
                    }
                }
                Assert.Equal(1, usedUrls.Count);


                // now we want to disable the client configuration and use the "default" ones

                store.Maintenance.Server.Send(
                    new PutServerWideClientConfigurationOperation(
#pragma warning disable 618
                        new ClientConfiguration {
                    MaxNumberOfRequestsPerSession = 10, PrettifyGeneratedLinqExpressions = false, ReadBalanceBehavior = Raven.Client.Http.ReadBalanceBehavior.None, Disabled = true
                }));
#pragma warning restore 618

                using (var session = store.OpenSession())
                {
                    session.Store(new User
                    {
                        Name = "Samson"
                    });
                    session.SaveChanges();
                }


                Assert.True(SpinWait.SpinUntil(() =>
                {
                    using (var session = store.OpenSession())
                    {
                        session.Load <User>("users/1"); // we need this to "pull" the new config
                        return(session.Advanced.RequestExecutor.Conventions.MaxNumberOfRequestsPerSession == 5);
                    }
                }, TimeSpan.FromSeconds(10)));

                await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                {
                    using (var session = store.OpenAsyncSession())
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            await session.StoreAsync(new User
                            {
                                Name = "Samson"
                            });
                            await session.SaveChangesAsync();
                        }
                    }
                });

                usedUrls.Clear();
                for (var i = 0; i < nodesCount; i++)
                {
                    using (var session = store.OpenSession())
                    {
                        Assert.True(usedUrls.Add((await session.Advanced.GetCurrentSessionNode()).Url.ToLower()));
                    }
                }
                Assert.Equal(nodesCount, usedUrls.Count);
            }
        }
        /// <summary>
        /// Removes the first element from the queue and returns it (or <c>null</c>).
        /// </summary>
        /// <param name="blockWhenEmpty">
        /// If <c>true</c> and the queue is empty, the calling thread is blocked until
        /// either an element is enqueued, or <see cref="Stop"/> is called.
        /// </param>
        /// <returns>
        /// <list type="bullet">
        ///   <item>
        ///     <term>If the queue not empty</term>
        ///     <description>the first element.</description>
        ///   </item>
        ///   <item>
        ///     <term>otherwise, if <paramref name="blockWhenEmpty"/>==<c>false</c>
        ///       or <see cref="Stop"/> has been called</term>
        ///     <description><c>null</c>.</description>
        ///   </item>
        /// </list>
        /// </returns>
        public Event Dequeue(bool blockWhenEmpty)
        {
            SpinWait sw = new SpinWait();

            do
            {
                int cachedRemoveId = _removeId;
                int cachedAddId    = _addId;

                // Empty case
                if (cachedRemoveId == cachedAddId)
                {
                    if (!blockWhenEmpty || _stopped != 0)
                    {
                        return(null);
                    }

                    // Spin a few times to see if something changes
                    if (sw.Count <= spinCount)
                    {
                        sw.SpinOnce();
                    }
                    else
                    {
                        // Reset to wait for an enqueue
                        _mreAdd.Reset();

                        // Recheck for an enqueue to avoid a Wait
                        if (cachedRemoveId != _removeId || cachedAddId != _addId)
                        {
                            // Queue is not empty, set the event
                            _mreAdd.Set();
                            continue;
                        }

                        // Wait for something to happen
                        _mreAdd.Wait(500);
                    }

                    continue;
                }

                // Validate that we are the current dequeuer
                if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
                {
                    continue;
                }


                // Dequeue our work item
                Event e;
                while (!_queue.TryDequeue(out e))
                {
                    if (!blockWhenEmpty || _stopped != 0)
                    {
                        return(null);
                    }
                }

                return(e);
            } while (true);
        }
示例#30
0
        void RunRenderWindow()
        {
            bool winStarted = false;
            Task winthread  = new Task(() =>
            {
                win        = new RenderWindow(renderer, midifile, settings);
                winStarted = true;
                win.Run();
            });

            winthread.Start();
            SpinWait.SpinUntil(() => winStarted);
            double    time      = 0;
            int       nc        = -1;
            long      maxRam    = 0;
            long      avgRam    = 0;
            long      ramSample = 0;
            Stopwatch timewatch = new Stopwatch();

            timewatch.Start();
            IPluginRender render      = null;
            double        lastWinTime = double.NaN;

            bool tryToParse()
            {
                lock (midifile)
                {
                    return((midifile.ParseUpTo(
                                (win.midiTime + win.lastDeltaTimeOnScreen +
                                 (win.tempoFrameStep * 20 * settings.tempoMultiplier * (win.lastMV > 1 ? win.lastMV : 1)))) ||
                            nc != 0) && settings.running);
                }
            }

            try
            {
                while (tryToParse())
                {
                    //SpinWait.SpinUntil(() => lastWinTime != win.midiTime || render != renderer.renderer || !settings.running);
                    if (!settings.running)
                    {
                        break;
                    }
                    Note   n;
                    double cutoffTime          = win.midiTime;
                    bool   manualDelete        = false;
                    double noteCollectorOffset = 0;
                    bool   receivedInfo        = false;
                    while (!receivedInfo)
                    {
                        try
                        {
                            render       = renderer.renderer;
                            receivedInfo = true;
                        }
                        catch
                        { }
                    }
                    manualDelete        = render.ManualNoteDelete;
                    noteCollectorOffset = render.NoteCollectorOffset;
                    cutoffTime         += noteCollectorOffset;
                    if (!settings.running)
                    {
                        break;
                    }
                    lock (midifile.globalDisplayNotes)
                    {
                        var i = midifile.globalDisplayNotes.Iterate();
                        if (manualDelete)
                        {
                            while (i.MoveNext(out n))
                            {
                                if (n.delete)
                                {
                                    i.Remove();
                                }
                                else
                                {
                                    nc++;
                                }
                            }
                        }
                        else
                        {
                            while (i.MoveNext(out n))
                            {
                                if (n.hasEnded && n.end < cutoffTime)
                                {
                                    i.Remove();
                                }
                                if (n.start > cutoffTime)
                                {
                                    break;
                                }
                            }
                        }
                        GC.Collect();
                    }
                    try
                    {
                        double progress = win.midiTime / midifile.maxTrackTime;
                        if (settings.timeBasedNotes)
                        {
                            progress = win.midiTime / 1000 / midifile.info.secondsLength;
                        }
                        Console.WriteLine(
                            Math.Round(progress * 10000) / 100 +
                            "\tNotes drawn: " + renderer.renderer.LastNoteCount +
                            "\tRender FPS: " + Math.Round(settings.liveFps) +
                            "\tNotes drawn: " + renderer.renderer.LastNoteCount
                            );
                    }
                    catch
                    {
                    }
                    long ram = Process.GetCurrentProcess().PrivateMemorySize64;
                    if (maxRam < ram)
                    {
                        maxRam = ram;
                    }
                    avgRam = (long)((double)avgRam * ramSample + ram) / (ramSample + 1);
                    ramSample++;
                    lastWinTime = win.midiTime;
                    Stopwatch s = new Stopwatch();
                    s.Start();
                    SpinWait.SpinUntil(() =>
                                       (
                                           (s.ElapsedMilliseconds > 1000.0 / settings.fps * 30 && false) ||
                                           (win.midiTime + win.lastDeltaTimeOnScreen +
                                            (win.tempoFrameStep * 10 * settings.tempoMultiplier * (win.lastMV > 1 ? win.lastMV : 1))) > midifile.currentSyncTime ||
                                           lastWinTime != win.midiTime || render != renderer.renderer || !settings.running
                                       )
                                       );;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while opeining render window. Please try again.\n\n" + ex.Message + "\n" + ex.StackTrace);
                settings.running = false;
            }
            winthread.GetAwaiter().GetResult();
            settings.running = false;
            Console.WriteLine("Reset midi file");
            midifile.Reset();
            win.Dispose();
            win = null;
            GC.Collect();
            GC.WaitForFullGCComplete();
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine(
                "Finished render\nRAM usage (Private bytes)\nPeak: " + Math.Round((double)maxRam / 1000 / 1000 / 1000 * 100) / 100 +
                "GB\nAvg: " + Math.Round((double)avgRam / 1000 / 1000 / 1000 * 100) / 100 +
                "GB\nMinutes to render: " + Math.Round((double)timewatch.ElapsedMilliseconds / 1000 / 60 * 100) / 100);
            Console.ResetColor();
            Dispatcher.Invoke(() =>
            {
                Resources["notRendering"]  = true;
                Resources["notPreviewing"] = true;
            });
        }
示例#31
0
 /// <summary>Wait until process exits.</summary>
 public void WaitForExit()
 {
     process.WaitForExit();
     SpinWait.SpinUntil(() => finished);
 }
示例#32
0
        //[Fact(Skip = "Outerloop")]
        public void RunActionBlockConformanceTests()
        {
            // SYNC
            // Do everything twice - once through OfferMessage and Once through Post
            for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
            {
                Func <DataflowBlockOptions, TargetProperties <int> > actionBlockFactory =
                    options =>
                {
                    ITargetBlock <int> target = new ActionBlock <int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options);
                    return(new TargetProperties <int> {
                        Target = target, Capturer = target, ErrorVerifyable = true
                    });
                };

                CancellationTokenSource cancellationSource = new CancellationTokenSource();
                var defaultOptions = new ExecutionDataflowBlockOptions();
                var dopOptions     = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                };
                var mptOptions = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 1
                };
                var cancellationOptions = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 1, CancellationToken = cancellationSource.Token
                };
                var spscOptions = new ExecutionDataflowBlockOptions {
                    SingleProducerConstrained = true
                };
                var spscMptOptions = new ExecutionDataflowBlockOptions {
                    SingleProducerConstrained = true, MaxMessagesPerTask = 10
                };

                Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, dopOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, mptOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, mptOptions, 1, Intervention.Complete, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, cancellationOptions, 1, Intervention.Cancel, cancellationSource, feedMethod, true));

                Assert.True(FeedTarget(actionBlockFactory, spscOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, spscOptions, 1, Intervention.Complete, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, spscMptOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, spscMptOptions, 1, Intervention.Complete, null, feedMethod, true));
            }

            // Test scheduler usage
            {
                bool localPassed = true;
                for (int trial = 0; trial < 2; trial++)
                {
                    var sts = new SimpleTaskScheduler();

                    var options = new ExecutionDataflowBlockOptions {
                        TaskScheduler = sts, MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, MaxMessagesPerTask = 1
                    };
                    if (trial == 0)
                    {
                        options.SingleProducerConstrained = true;
                    }

                    var ab = new ActionBlock <int>(i => localPassed &= TaskScheduler.Current.Id == sts.Id, options);
                    for (int i = 0; i < 2; i++)
                    {
                        ab.Post(i);
                    }
                    ab.Complete();
                    ab.Completion.Wait();
                }

                Assert.True(localPassed, string.Format("{0}: Correct scheduler usage", localPassed ? "Success" : "Failure"));
            }

            // Test count
            {
                bool localPassed = true;
                for (int trial = 0; trial < 2; trial++)
                {
                    var barrier1 = new Barrier(2);
                    var barrier2 = new Barrier(2);
                    var ab       = new ActionBlock <int>(i =>
                    {
                        barrier1.SignalAndWait();
                        barrier2.SignalAndWait();
                    }, new ExecutionDataflowBlockOptions {
                        SingleProducerConstrained = (trial == 0)
                    });
                    for (int iter = 0; iter < 2; iter++)
                    {
                        for (int i = 1; i <= 2; i++)
                        {
                            ab.Post(i);
                        }
                        for (int i = 1; i >= 0; i--)
                        {
                            barrier1.SignalAndWait();
                            localPassed &= i == ab.InputCount;
                            barrier2.SignalAndWait();
                        }
                    }
                }

                Assert.True(localPassed, string.Format("{0}: InputCount", localPassed ? "Success" : "Failure"));
            }

            // Test ordering
            {
                bool localPassed = true;
                for (int trial = 0; trial < 2; trial++)
                {
                    int prev = -1;
                    var ab   = new ActionBlock <int>(i =>
                    {
                        if (prev + 1 != i)
                        {
                            localPassed &= false;
                        }
                        prev = i;
                    }, new ExecutionDataflowBlockOptions {
                        SingleProducerConstrained = (trial == 0)
                    });
                    for (int i = 0; i < 2; i++)
                    {
                        ab.Post(i);
                    }
                    ab.Complete();
                    ab.Completion.Wait();
                }

                Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
            }

            // Test non-greedy
            {
                bool localPassed = true;
                var  barrier     = new Barrier(2);
                var  ab          = new ActionBlock <int>(i =>
                {
                    barrier.SignalAndWait();
                }, new ExecutionDataflowBlockOptions {
                    BoundedCapacity = 1
                });
                ab.SendAsync(1);
                Task.Delay(200).Wait();
                var sa2 = ab.SendAsync(2);
                localPassed &= !sa2.IsCompleted;
                barrier.SignalAndWait(); // for SendAsync(1)
                barrier.SignalAndWait(); // for SendAsync(2)
                localPassed &= sa2.Wait(100);
                int total = 0;
                ab = new ActionBlock <int>(i =>
                {
                    Interlocked.Add(ref total, i);
                    Task.Delay(1).Wait();
                }, new ExecutionDataflowBlockOptions {
                    BoundedCapacity = 1
                });
                for (int i = 1; i <= 100; i++)
                {
                    ab.SendAsync(i);
                }
                SpinWait.SpinUntil(() => total == ((100 * 101) / 2), 30000);
                localPassed &= total == ((100 * 101) / 2);
                Assert.True(localPassed, string.Format("total={0} (must be {1})", total, (100 * 101) / 2));
                Assert.True(localPassed, string.Format("{0}: Non-greedy support", localPassed ? "Success" : "Failure"));
            }

            // Test that OperationCanceledExceptions are ignored
            {
                bool localPassed = true;
                for (int trial = 0; trial < 2; trial++)
                {
                    int sumOfOdds = 0;
                    var ab        = new ActionBlock <int>(i =>
                    {
                        if ((i % 2) == 0)
                        {
                            throw new OperationCanceledException();
                        }
                        sumOfOdds += i;
                    }, new ExecutionDataflowBlockOptions {
                        SingleProducerConstrained = (trial == 0)
                    });
                    for (int i = 0; i < 4; i++)
                    {
                        ab.Post(i);
                    }
                    ab.Complete();
                    ab.Completion.Wait();
                    localPassed = sumOfOdds == (1 + 3);
                }

                Assert.True(localPassed, string.Format("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"));
            }

            // Test using a precanceled token
            {
                bool localPassed = true;
                try
                {
                    var cts = new CancellationTokenSource();
                    cts.Cancel();
                    var dbo = new ExecutionDataflowBlockOptions {
                        CancellationToken = cts.Token
                    };
                    var ab = new ActionBlock <int>(i => { }, dbo);

                    localPassed &= ab.Post(42) == false;
                    localPassed &= ab.InputCount == 0;
                    localPassed &= ab.Completion != null;
                    ab.Complete();
                }
                catch (Exception)
                {
                    localPassed = false;
                }

                Assert.True(localPassed, string.Format("{0}: Precanceled tokens work correctly", localPassed ? "Success" : "Failure"));
            }

            // Test faulting
            {
                bool localPassed = true;
                for (int trial = 0; trial < 2; trial++)
                {
                    var ab = new ActionBlock <int>(i => { throw new InvalidOperationException(); },
                                                   new ExecutionDataflowBlockOptions {
                        SingleProducerConstrained = (trial == 0)
                    });
                    ab.Post(42);
                    ab.Post(1);
                    ab.Post(2);
                    ab.Post(3);
                    try { localPassed &= ab.Completion.Wait(5000); }
                    catch { }
                    localPassed &= ab.Completion.IsFaulted;
                    localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
                    localPassed &= ab.Post(4) == false;
                }

                Assert.True(localPassed, string.Format("{0}: Faulted handled correctly", localPassed ? "Success" : "Failure"));
            }

            // ASYNC (a copy of the sync but with constructors returning Task instead of void

            // Do everything twice - once through OfferMessage and Once through Post
            for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
            {
                Func <DataflowBlockOptions, TargetProperties <int> > actionBlockFactory =
                    options =>
                {
                    ITargetBlock <int> target = new ActionBlock <int>(i => TrackCapturesAsync(i), (ExecutionDataflowBlockOptions)options);
                    return(new TargetProperties <int> {
                        Target = target, Capturer = target, ErrorVerifyable = true
                    });
                };
                CancellationTokenSource cancellationSource = new CancellationTokenSource();
                var defaultOptions = new ExecutionDataflowBlockOptions();
                var dopOptions     = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                };
                var mptOptions = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10
                };
                var cancellationOptions = new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token
                };

                Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true));
                Assert.True(FeedTarget(actionBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true));
            }

            // Test scheduler usage
            {
                bool localPassed = true;
                var  sts         = new SimpleTaskScheduler();
                var  ab          = new ActionBlock <int>(i =>
                {
                    localPassed &= TaskScheduler.Current.Id == sts.Id;
                    return(Task.Factory.StartNew(() => { }));
                }, new ExecutionDataflowBlockOptions {
                    TaskScheduler = sts, MaxDegreeOfParallelism = -1, MaxMessagesPerTask = 10
                });
                for (int i = 0; i < 2; i++)
                {
                    ab.Post(i);
                }
                ab.Complete();
                ab.Completion.Wait();
                Assert.True(localPassed, string.Format("{0}: Correct scheduler usage", localPassed ? "Success" : "Failure"));
            }

            // Test count
            {
                bool localPassed = true;
                var  barrier1    = new Barrier(2);
                var  barrier2    = new Barrier(2);
                var  ab          = new ActionBlock <int>(i => Task.Factory.StartNew(() =>
                {
                    barrier1.SignalAndWait();
                    barrier2.SignalAndWait();
                }));
                for (int iter = 0; iter < 2; iter++)
                {
                    for (int i = 1; i <= 2; i++)
                    {
                        ab.Post(i);
                    }
                    for (int i = 1; i >= 0; i--)
                    {
                        barrier1.SignalAndWait();
                        localPassed &= i == ab.InputCount;
                        barrier2.SignalAndWait();
                    }
                }
                Assert.True(localPassed, string.Format("{0}: InputCount", localPassed ? "Success" : "Failure"));
            }

            // Test ordering
            {
                bool localPassed = true;
                int  prev        = -1;
                var  ab          = new ActionBlock <int>(i =>
                {
                    return(Task.Factory.StartNew(() =>
                    {
                        if (prev + 1 != i)
                        {
                            localPassed &= false;
                        }
                        prev = i;
                    }));
                });
                for (int i = 0; i < 2; i++)
                {
                    ab.Post(i);
                }
                ab.Complete();
                ab.Completion.Wait();
                Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
            }

            // Test non-greedy
            {
                bool localPassed = true;
                var  barrier     = new Barrier(2);
                var  ab          = new ActionBlock <int>(i =>
                {
                    return(Task.Factory.StartNew(() =>
                    {
                        barrier.SignalAndWait();
                    }));
                }, new ExecutionDataflowBlockOptions {
                    BoundedCapacity = 1
                });
                ab.SendAsync(1);
                Task.Delay(200).Wait();
                var sa2 = ab.SendAsync(2);
                localPassed &= !sa2.IsCompleted;
                barrier.SignalAndWait(); // for SendAsync(1)
                barrier.SignalAndWait(); // for SendAsync(2)
                localPassed &= sa2.Wait(100);
                int total = 0;
                ab = new ActionBlock <int>(i =>
                {
                    return(Task.Factory.StartNew(() =>
                    {
                        Interlocked.Add(ref total, i);
                        Task.Delay(1).Wait();
                    }));
                }, new ExecutionDataflowBlockOptions {
                    BoundedCapacity = 1
                });
                for (int i = 1; i <= 100; i++)
                {
                    ab.SendAsync(i);
                }
                SpinWait.SpinUntil(() => total == ((100 * 101) / 2), 30000);
                localPassed &= total == ((100 * 101) / 2);
                Assert.True(localPassed, string.Format("total={0} (must be {1})", total, (100 * 101) / 2));
                Assert.True(localPassed, string.Format("{0}: Non-greedy support", localPassed ? "Success" : "Failure"));
            }

            // Test that OperationCanceledExceptions are ignored
            {
                bool localPassed = true;
                int  sumOfOdds   = 0;
                var  ab          = new ActionBlock <int>(i =>
                {
                    if ((i % 2) == 0)
                    {
                        throw new OperationCanceledException();
                    }
                    return(Task.Factory.StartNew(() => { sumOfOdds += i; }));
                });
                for (int i = 0; i < 4; i++)
                {
                    ab.Post(i);
                }
                ab.Complete();
                ab.Completion.Wait();
                localPassed = sumOfOdds == (1 + 3);
                Assert.True(localPassed, string.Format("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"));
            }

            // Test that null task is ignored
            {
                bool localPassed = true;
                int  sumOfOdds   = 0;
                var  ab          = new ActionBlock <int>(i =>
                {
                    if ((i % 2) == 0)
                    {
                        return(null);
                    }
                    return(Task.Factory.StartNew(() => { sumOfOdds += i; }));
                });
                for (int i = 0; i < 4; i++)
                {
                    ab.Post(i);
                }
                ab.Complete();
                ab.Completion.Wait();
                localPassed = sumOfOdds == (1 + 3);
                Assert.True(localPassed, string.Format("{0}: null tasks are ignored", localPassed ? "Success" : "Failure"));
            }

            // Test faulting from the delegate
            {
                bool localPassed = true;
                var  ab          = new ActionBlock <int>(new Func <int, Task>(i => { throw new InvalidOperationException(); }));
                ab.Post(42);
                ab.Post(1);
                ab.Post(2);
                ab.Post(3);
                try { localPassed &= ab.Completion.Wait(100); }
                catch { }
                localPassed &= ab.Completion.IsFaulted;
                localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
                localPassed &= ab.Post(4) == false;
                Assert.True(localPassed, string.Format("{0}: Faulted from delegate handled correctly", localPassed ? "Success" : "Failure"));
            }

            // Test faulting from the task
            {
                bool localPassed = true;
                var  ab          = new ActionBlock <int>(i => Task.Factory.StartNew(() => { throw new InvalidOperationException(); }));
                ab.Post(42);
                ab.Post(1);
                ab.Post(2);
                ab.Post(3);
                try { localPassed &= ab.Completion.Wait(100); }
                catch { }
                localPassed &= ab.Completion.IsFaulted;
                localPassed &= SpinWait.SpinUntil(() => ab.InputCount == 0, 500);
                localPassed &= ab.Post(4) == false;
                Assert.True(localPassed, string.Format("{0}: Faulted from task handled correctly", localPassed ? "Success" : "Failure"));
            }
        }
示例#33
0
        private void ProcessMeasurements()
        {
            List <IMeasurement> measurements = new List <IMeasurement>((int)(Ticks.ToSeconds(GapThreshold) * m_sampleRate * m_channels * 1.1D));

            LittleBinaryValue[] sample;

            while (Enabled)
            {
                try
                {
                    SpinWait spinner = new SpinWait();

                    // Determine what time it is now
                    long now = DateTime.UtcNow.Ticks;

                    // Assign a timestamp to the next sample based on its location
                    // in the file relative to the other samples in the file
                    long timestamp = m_startTime + (m_dataIndex * Ticks.PerSecond / m_sampleRate);

                    if (now - timestamp > GapThreshold)
                    {
                        // Reset the start time and delay next transmission in an attempt to catch up
                        m_startTime = now - (m_dataIndex * Ticks.PerSecond / m_sampleRate) + Ticks.FromSeconds(RecoveryDelay);
                        timestamp   = now;
                        OnStatusMessage(MessageLevel.Info, "Start time reset.");
                    }

                    // Keep generating measurements until
                    // we catch up to the current time.
                    while (timestamp < now)
                    {
                        sample = m_dataReader.GetNextSample();

                        // If the sample is null, we've reached the end of the file - close and reopen,
                        // resetting the data index and start time
                        if (sample == null)
                        {
                            m_dataReader.Close();
                            m_dataReader.Dispose();

                            m_dataReader = OpenWaveDataReader();
                            m_dataIndex  = 0;

                            m_startTime = timestamp;
                            sample      = m_dataReader.GetNextSample();
                        }

                        // Create new measurements, one for each channel, and add them to the measurements list
                        for (int i = 0; i < m_channels; i++)
                        {
                            measurements.Add(Measurement.Clone(OutputMeasurements[i], sample[i].ConvertToType(TypeCode.Double), timestamp));
                        }

                        // Update the data index and recalculate the assigned timestamp for the next sample
                        m_dataIndex++;
                        timestamp = m_startTime + (m_dataIndex * Ticks.PerSecond / m_sampleRate);
                    }

                    OnNewMeasurements(measurements);
                    measurements.Clear();

                    while (DateTime.UtcNow.Ticks - timestamp <= GapThreshold / 100)
                    {
                        // Ahead of schedule -- pause for a moment
                        spinner.SpinOnce();
                    }
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, ex);
                }
            }
        }
        public async Task PushServiceTest()
        {
            var tempFolder = CreateTemporaryDirectory();

            // Copy all files in the P4_Prostate directory to the temporary directory
            Directory.EnumerateFiles(@"Images\1ValidSmall\")
            .Select(x => new FileInfo(x))
            .ToList()
            .ForEach(x => x.CopyTo(Path.Combine(tempFolder.FullName, x.Name)));

            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 108, "127.0.0.1");
            var resultDirectory   = CreateTemporaryDirectory();

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var dataSender = new DicomDataSender();
                var echoResult = await dataSender.DicomEchoAsync("RListener", applicationEntity.Title, applicationEntity.Port, applicationEntity.IpAddress);

                // Check echo
                Assert.IsTrue(echoResult == DicomOperationResult.Success);

                var testAETConfigModel = GetTestAETConfigModel();

                using (var deleteService = CreateDeleteService())
                    using (var pushService = CreatePushService())
                        using (var pushQueue = pushService.PushQueue)
                        {
                            deleteService.Start();
                            pushService.Start();

                            TransactionalEnqueue(
                                pushQueue,
                                new PushQueueItem(
                                    destinationApplicationEntity: applicationEntity,
                                    calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                    callingApplicationEntityTitle: applicationEntity.Title,
                                    associationGuid: Guid.NewGuid(),
                                    associationDateTime: DateTime.UtcNow,
                                    filePaths: tempFolder.GetFiles().Select(x => x.FullName).ToArray()));

                            // Wait for all events to finish on the data received
                            SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

                            SpinWait.SpinUntil(() => new DirectoryInfo(tempFolder.FullName).Exists == false, TimeSpan.FromSeconds(30));

                            Assert.IsFalse(new DirectoryInfo(tempFolder.FullName).Exists);

                            Assert.AreEqual(20, resultDirectory.GetDirectories()[0].GetFiles().Length);
                        }
            }
        }
示例#35
0
 public void Flush()
 {
     SpinWait.SpinUntil(() => this.TrySendDisposition());
 }
示例#36
0
        /// <summary>
        /// Builds the specified project.
        /// </summary>
        /// <param name="project">The project to build.</param>
        /// <param name="cancellation">Cancellation token to cancel the wait for the build to finish.</param>
        /// <param name="timeout">A maximum time to wait for the build to finish.</param>
        /// <exception cref="System.ArgumentException">The project has no <see cref="ISolutionExplorerNode.OwningSolution"/>.</exception>
        /// <returns><see langword="true"/> if the build succeeded; <see langword="false"/> otherwise.</returns>
        public static Task <bool> Build(this IProjectNode project, CancellationToken cancellation, TimeSpan timeout)
        {
            Guard.NotNull(() => project, project);
            Guard.NotNull(() => cancellation, cancellation);

            var solution = project.OwningSolution;

            if (solution == null)
            {
                throw new ArgumentException(Strings.IProjectNodeExtensions.BuildNoSolution(project.DisplayName));
            }

            var sln = solution.As <EnvDTE.Solution>();

            if (sln == null)
            {
                throw new ArgumentException(Strings.IProjectNodeExtensions.BuildNoSolution(project.DisplayName));
            }

            return(System.Threading.Tasks.Task.Factory.StartNew <bool>(() =>
            {
                try
                {
                    // Let build run async.
                    sln.SolutionBuild.BuildProject(sln.SolutionBuild.ActiveConfiguration.Name, project.As <EnvDTE.Project>().UniqueName, false);

                    // First wait until it becomes in progress. We give it
                    // a maximum of 2 seconds for VS to start building. If this doesn't
                    // happen in that time, something really weird must be going on.
                    var inProgress = SpinWait.SpinUntil(() =>
                                                        cancellation.IsCancellationRequested ||
                                                        sln.SolutionBuild.BuildState == EnvDTE.vsBuildState.vsBuildStateInProgress,
                                                        2000);

                    // If the build did not start in under 2 seconds, something weird happened,
                    // so return quickly and with false.
                    // Note that this may be the case when the token is cancelled.
                    if (!inProgress)
                    {
                        return false;
                    }

                    // Next wait until it's done.
                    // This could be a remote build, complex one, etc., so we specify 10 minutes as a
                    // conservative wait.
                    var isDone = SpinWait.SpinUntil(() =>
                                                    cancellation.IsCancellationRequested ||
                                                    sln.SolutionBuild.BuildState == EnvDTE.vsBuildState.vsBuildStateDone,
                                                    timeout);

                    // LastBuildInfo == # of projects that failed to build.
                    // We'll return false if the build wait was cancelled.
                    return !cancellation.IsCancellationRequested && isDone && sln.SolutionBuild.LastBuildInfo == 0;
                }
                catch (Exception ex)
                {
                    tracer.Error(ex, Strings.IProjectNodeExtensions.BuildException);
                    return false;
                }
            }, cancellation, TaskCreationOptions.None, TaskScheduler.Default));
        }
示例#37
0
        void UIthread()
        {
            while (true)
            {
                Action dele = delegate()
                {
                    UpdateUI();

                    //prevent maximizing
                    if (this.WindowState != WindowState.Maximized)
                    {
                        this.WindowState = WindowState.Normal;
                    }

                    //get window information
                    if (recorder.Capturing())
                    {
                        if (graph.GetIntPtr() != IntPtr.Zero)
                        {
                            try
                            {
                                displayer.ImageBox.Source = Imaging.CreateBitmapSourceFromHBitmap(graph.GetIntPtr(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                                graph.DeleteIntPtr();
                            }
                            catch { }
                        }

                        if (area_window.IsVisible)
                        {
                            graph.Shift(area_window.Left, area_window.Top);
                        }

                        if (recorder.Recording())
                        {
                            if (appmani.IsTargetActive())
                            {
                                RecordButton.Background = Brushes.Red;

                                if (ffmpeg.IsWrited())
                                {
                                    notify.Icon = Properties.Resources.notify_writing;
                                }
                                else
                                {
                                    notify.Icon = Properties.Resources.notify_capturing;
                                }
                            }
                            else
                            {
                                RecordButton.Background = Brushes.IndianRed;
                                notify.Icon             = Properties.Resources.notify_norm;
                            }
                        }
                    }
                    else if (!appmani.Lock())
                    {
                        appmani.SetTargetToNextWindow();
                    }
                };
                Dispatcher.Invoke(dele);

                //Thread.Sleep(65);
                SpinWait.SpinUntil(() => false, 65);
            }
        }
示例#38
0
        public void Authenticate_should_not_throw_when_authentication_succeeds(
            [Values(false, true)] bool useSpeculativeAuthenticate,
            [Values(false, true)] bool useLongAuthentication,
            [Values(false, true)] bool async)
        {
            var randomStringGenerator = new ConstantRandomStringGenerator(_clientNonce);
            var subject = new ScramSha256Authenticator(__credential, randomStringGenerator, serverApi: null);

            var saslStartReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                @"{ conversationId : 1," +
                                                                                $"  payload : BinData(0,'{ToUtf8Base64(__serverResponse1)}')," +
                                                                                @"  done : false,
                    ok : 1 }"));
            var saslContinueReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                   @"{ conversationId : 1," +
                                                                                   $"  payload : BinData(0,'{ToUtf8Base64(__serverResponse2)}')," +
                                                                                   $"  done : {new BsonBoolean(!useLongAuthentication)}," +
                                                                                   @"  ok : 1 }"));
            var saslLastStepReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                   @"{ conversationId : 1," +
                                                                                   $"  payload : BinData(0,'{ToUtf8Base64(__serverOptionalFinalResponse)}')," +
                                                                                   @"  done : true,
                    ok : 1 }"));

            var connection     = new MockConnection(__serverId);
            var isMasterResult = (BsonDocument)__descriptionQueryWireProtocol.IsMasterResult.Wrapped.Clone();

            if (useSpeculativeAuthenticate)
            {
                isMasterResult.Add("speculativeAuthenticate", saslStartReply.Documents[0].ToBsonDocument());
            }

            /* set buildInfoResult to 3.4 to force authenticator to use Query Message Wire Protocol because MockConnection
             * does not support OP_MSG */
            connection.Description = new ConnectionDescription(
                __descriptionQueryWireProtocol.ConnectionId,
                new IsMasterResult(isMasterResult),
                new BuildInfoResult(new BsonDocument("version", "3.4")));

            BsonDocument isMasterCommand = null;

            if (useSpeculativeAuthenticate)
            {
                // We must call CustomizeIsMasterCommand so that the authenticator thinks its started to speculatively
                // authenticate
                isMasterCommand = subject.CustomizeInitialIsMasterCommand(new BsonDocument {
                    { "isMaster", 1 }
                });
            }
            else
            {
                connection.EnqueueReplyMessage(saslStartReply);
            }

            connection.EnqueueReplyMessage(saslContinueReply);
            if (useLongAuthentication)
            {
                connection.EnqueueReplyMessage(saslLastStepReply);
            }

            var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1;

            Exception exception;

            if (async)
            {
                exception = Record.Exception(
                    () => subject.AuthenticateAsync(connection, connection.Description, CancellationToken.None)
                    .GetAwaiter().GetResult());
            }
            else
            {
                exception = Record.Exception(
                    () => subject.Authenticate(connection, connection.Description, CancellationToken.None));
            }

            exception.Should().BeNull();
            var expectedSentMessageCount = 3 - (useLongAuthentication ? 0 : 1) - (useSpeculativeAuthenticate ? 1 : 0);

            SpinWait.SpinUntil(
                () => connection.GetSentMessages().Count >= expectedSentMessageCount,
                TimeSpan.FromSeconds(5)
                ).Should().BeTrue();

            var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages());

            sentMessages.Count.Should().Be(expectedSentMessageCount);

            var actualRequestIds = sentMessages.Select(m => m["requestId"].AsInt32).ToList();

            for (var i = 0; i != actualRequestIds.Count; ++i)
            {
                actualRequestIds[i].Should().BeInRange(expectedRequestId + i, expectedRequestId + 10 + i);
            }

            var expectedMessages = new List <BsonDocument>();

            var saslStartMessage = BsonDocument.Parse(
                @"{ opcode : 'query'," +
                $"  requestId : {actualRequestIds[0]}," +
                @"  database : 'source',
                    collection : '$cmd',
                    batchSize : -1,
                    slaveOk : true,
                    query : { saslStart : 1,
                              mechanism : 'SCRAM-SHA-256'," +
                $"            payload : new BinData(0, '{ToUtf8Base64(__clientRequest1)}')" +
                @"            options : { skipEmptyExchange: true }}}");

            if (!useSpeculativeAuthenticate)
            {
                expectedMessages.Add(saslStartMessage);
            }

            var saslContinueMessage = BsonDocument.Parse(
                @"{ opcode : 'query'," +
                $"  requestId : {(useSpeculativeAuthenticate ? actualRequestIds[0] : actualRequestIds[1])}," +
                @"  database : 'source',
                    collection : '$cmd',
                    batchSize : -1,
                    slaveOk : true,
                    query : { saslContinue : 1,
                              conversationId : 1, " +
                $"            payload : new BinData(0, \"{ToUtf8Base64(__clientRequest2)}\")}}}}");

            expectedMessages.Add(saslContinueMessage);

            if (useLongAuthentication)
            {
                var saslOptionalFinalMessage = BsonDocument.Parse(
                    @"{ opcode : 'query'," +
                    $"  requestId : {(useSpeculativeAuthenticate ? actualRequestIds[1] : actualRequestIds[2])}," +
                    @"  database : 'source',
                        collection : '$cmd',
                        batchSize : -1,
                        slaveOk : true,
                        query : { saslContinue : 1,
                                  conversationId : 1, " +
                    $"            payload : new BinData(0, '{ToUtf8Base64(__clientOptionalFinalRequest)}')}}}}");
                expectedMessages.Add(saslOptionalFinalMessage);
            }

            sentMessages.Should().Equal(expectedMessages);
            if (useSpeculativeAuthenticate)
            {
                isMasterCommand.Should().Contain("speculativeAuthenticate");
                var speculativeAuthenticateDocument         = isMasterCommand["speculativeAuthenticate"].AsBsonDocument;
                var expectedSpeculativeAuthenticateDocument =
                    saslStartMessage["query"].AsBsonDocument.Add("db", __credential.Source);
                speculativeAuthenticateDocument.Should().Be(expectedSpeculativeAuthenticateDocument);
            }
        }
示例#39
0
 /// <summary>
 /// Wait until page initialization
 /// </summary>
 private void PageInitialize()
 {
     SpinWait.SpinUntil(() => Page.IsBrowserInitialized);
 }
示例#40
0
        private void RunTestIteration(SqlConnection con, SqlRandomizer rand, SqlRandomTable table, string tableName)
        {
            // random list of columns
            int columnCount = table.Columns.Count;

            int[] columnIndices = rand.NextIndices(columnCount);
            int   selectedCount = rand.NextIntInclusive(1, maxValueInclusive: columnCount);

            StringBuilder selectBuilder = new StringBuilder();

            table.GenerateSelectFromTableTSql(tableName, selectBuilder, columnIndices, 0, selectedCount);
            SqlCommand cmd = con.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = selectBuilder.ToString();

            bool cancel = rand.Next(100) == 0; // in 1% of the cases, call Cancel

            if (cancel)
            {
                int cancelAfterMilliseconds = rand.Next(5);
                int cancelAfterSpinCount    = rand.Next(1000);

                ThreadPool.QueueUserWorkItem((object state) =>
                {
                    for (int i = 0; cancel && i < cancelAfterMilliseconds; i++)
                    {
                        Thread.Sleep(1);
                    }
                    if (cancel && cancelAfterSpinCount > 0)
                    {
                        SpinWait.SpinUntil(() => false, new TimeSpan(cancelAfterSpinCount));
                    }
                    if (cancel)
                    {
                        cmd.Cancel();
                    }
                });
            }

            int             readerRand     = rand.NextIntInclusive(0, maxValueInclusive: 256);
            CommandBehavior readerBehavior = CommandBehavior.Default;

            if (readerRand % 10 == 0)
            {
                readerBehavior = CommandBehavior.SequentialAccess;
            }
            try
            {
                using (SqlDataReader reader = cmd.ExecuteReader(readerBehavior))
                {
                    int row = 0;
                    while (reader.Read())
                    {
                        int rowRand = rand.NextIntInclusive();
                        if (rowRand % 1000 == 0)
                        {
                            // abandon this reader
                            break;
                        }
                        else if (rowRand % 25 == 0)
                        {
                            // skip the row
                            row++;
                            continue;
                        }

                        IList <object> expectedRow = table[row];
                        for (int c = 0; c < reader.FieldCount; c++)
                        {
                            if (rand.NextIntInclusive(0, maxValueInclusive: 10) == 0)
                            {
                                // skip the column
                                continue;
                            }

                            int    expectedTableColumn = columnIndices[c];
                            object expectedValue       = expectedRow[expectedTableColumn];
                            if (table.Columns[expectedTableColumn].CanCompareValues)
                            {
                                Assert.True(expectedValue != null, "FAILED: Null is expected with CanCompareValues");

                                // read the value same way it was written
                                object actualValue = table.Columns[expectedTableColumn].Read(reader, c, expectedValue.GetType());
                                Assert.True(table.Columns[expectedTableColumn].CompareValues(expectedValue, actualValue),
                                            string.Format("FAILED: Data Comparison Failure:\n{0}", table.Columns[expectedTableColumn].BuildErrorMessage(expectedValue, actualValue)));
                            }
                        }

                        row++;
                    }
                }

                // keep last - this will stop the cancel task, if it is still active
                cancel = false;
            }
            catch (SqlException e)
            {
                if (!cancel)
                {
                    throw;
                }

                bool expected = false;

                foreach (SqlError error in e.Errors)
                {
                    if (error.Message == _operationCanceledErrorMessage)
                    {
                        // ignore this one - expected if canceled
                        expected = true;
                        break;
                    }
                    else if (error.Message == _severeErrorMessage)
                    {
                        // A severe error occurred on the current command.  The results, if any, should be discarded.
                        expected = true;
                        break;
                    }
                }

                if (!expected)
                {
                    // rethrow to the user
                    foreach (SqlError error in e.Errors)
                    {
                        Console.WriteLine("{0} {1}", error.Number, error.Message);
                    }
                    throw;
                }
            }
            catch (InvalidOperationException e)
            {
                bool expected = false;

                if (e.Message == _operationCanceledErrorMessage)
                {
                    // "Operation canceled" exception is raised as a SqlException (as one of SqlError objects) and as InvalidOperationException
                    expected = true;
                }

                if (!expected)
                {
                    throw;
                }
            }
        }
示例#41
0
        private void Cleanup()
        {
            while (true)
            {
                if (!this._cts.IsCancellationRequested)
                {
                    //Thread.Sleep(10);
                }

                Segment oldSegment = (Segment)this._currentSegment;
                if (Thread.VolatileRead(ref oldSegment.Count) > 100 || this._cts.IsCancellationRequested)
                {
                    bool    isCancellationRequested = this._cts.IsCancellationRequested;
                    Segment newSegment = new Segment();
                    Thread.VolatileWrite(ref this._currentSegment, newSegment);
                    this.Exchanges++;

                    using (FileStream fs = new FileStream(this._fileName, FileMode.Append, FileAccess.Write, FileShare.None, 1024 * 1024, FileOptions.WriteThrough))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            string msg;
                            while (oldSegment.Queue.TryDequeue(out msg))
                            {
                                sw.WriteLine(msg);
                                this.RecordsWritten++;
                            }

                            if (Thread.VolatileRead(ref oldSegment.RefCount) > 0)
                            {
                                //this.RefCount1++;
                                SpinWait.SpinUntil(() => { return(Thread.VolatileRead(ref oldSegment.RefCount) == 0); }, 10);
                                if (Thread.VolatileRead(ref oldSegment.RefCount) > 0)
                                {
                                    //this.RefCount2++;
                                    Thread.Yield();
                                    if (Thread.VolatileRead(ref oldSegment.RefCount) > 0)
                                    {
                                        //this.RefCount3++;
                                        SpinWait.SpinUntil(() => { return(Thread.VolatileRead(ref oldSegment.RefCount) == 0); });
                                    }
                                }

                                while (oldSegment.Queue.TryDequeue(out msg))
                                {
                                    sw.WriteLine(msg);
                                    this.RecordsWritten++;
                                }
                            }


                            sw.Flush();
                            fs.Flush();
                        }
                    }

                    if (this._cts.IsCancellationRequested && isCancellationRequested)
                    {
                        break;
                    }
                }
            }
        }
示例#42
0
        static void Main(string[] args)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + "\\Log");

            var storeMore = "";
            int tCnt      = _thread;

            log.Info("***************************************************");
            log.Info("Server Host Address: " + _storeServerHost);
            log.Info("Server Port: " + _storeServerPort);
            log.Info("Server AE Title: " + _storeServerAET);
            log.Info("Client AE Title: " + _aet);
            log.Info("Test count: " + _count);
            log.Info("Test interval: " + _interval);
            log.Info("Test thread: " + _thread);
            log.Info("Test dicom: " + _testDICOMPath);
            log.Info("***************************************************");
            if (_manual == "Y")
            {
                tCnt = 1;
                log.Info("To start test, enter \"y\"; Othersie, press any key to exit: ");
                storeMore = Console.ReadLine().Trim();
                if (storeMore.Length > 0 && storeMore.ToLower()[0] == 'y')
                {
                }
                else
                {
                    Environment.Exit(0);
                }
            }

            Thread[] workerThreads = new Thread[tCnt];

            for (int i = 0; i < workerThreads.Length; i++)
            {
                int tNum = i;
                workerThreads[i] = new Thread(new ThreadStart(async() =>
                {
                    //var client = new DicomClient(_storeServerHost, _storeServerPort, false, _aet, _storeServerAET);
                    //Add a handler to be notified of any association rejections
                    //client.AssociationRejected += (sender, e) => {
                    //    log.Warn($"Association was rejected. Rejected Reason:{e.Reason}");
                    //};

                    //Add a handler to be notified of any association information on successful connections
                    //client.AssociationAccepted += (sender, e) =>
                    //{
                    //    log.Info(($"Association was accepted by:{e.Association.RemoteHost}");
                    //};

                    //Add a handler to be notified when association is successfully released - this can be triggered by the remote peer as well
                    //client.AssociationReleased += (sender, e) => {
                    //    log.Info("Association was released. BYE BYE!");
                    //};
                    //client.RequestTimedOut += (sender, e) =>
                    //{
                    //    log.Warn($"Send PACS error exception:{e.Request} {e.Timeout}");
                    //    throw new NotImplementedException();
                    //};
                    //client.NegotiateAsyncOps();

                    int count = 0;
                    while ((_manual == "Y" && storeMore.Length > 0 && storeMore.ToLower()[0] == 'y') || (_manual != "Y" && count < _count))
                    {
                        try
                        {
                            var client = new DicomClient(_storeServerHost, _storeServerPort, false, _aet, _storeServerAET);
                            client.NegotiateAsyncOps();

                            string dicomFile = _testDICOMPath;

                            if (_manual == "Y")
                            {
                                while (!File.Exists(dicomFile))
                                {
                                    log.Warn("Invalid file path, enter the path for a DICOM file or press Enter to Exit:");

                                    dicomFile = Console.ReadLine();

                                    if (string.IsNullOrWhiteSpace(dicomFile))
                                    {
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                if (!File.Exists(dicomFile))
                                {
                                    log.Warn("Invalid file path, check test dicom file: " + _testDICOMPath);
                                    return;
                                }
                            }

                            if (_manual != "Y")
                            {
                                log.Info("Test " + tNum + "-[" + (count + 1) + "]");
                            }

                            var request = new DicomCStoreRequest(dicomFile);

                            request.OnResponseReceived += (req, response) =>
                            {
                                if (_manual == "Y")
                                {
                                    log.Info("C-Store Response Received, Status: " + response.Status);
                                    log.Info("To test again, enter \"y\"; Othersie, press any key to exit: ");
                                    storeMore = Console.ReadLine().Trim();
                                    if (storeMore.Length > 0 && storeMore.ToLower()[0] == 'y')
                                    {
                                    }
                                    else
                                    {
                                        Environment.Exit(0);
                                    }
                                }
                                else
                                {
                                    log.Info(tNum + "-[" + (count + 1) + "] " + "C-Store Response Received, Status: " + response.Status);
                                    if (count < (_count - 1))
                                    {
                                        int fortimerinterval = 0;
                                        if (_interval == "random")
                                        {
                                            fortimerinterval = rand.Next(_randomIntervalmin, _randomIntervalmax);
                                        }
                                        else
                                        {
                                            fortimerinterval = Int32.Parse(_interval);
                                        }
                                        log.Info(tNum + "-[" + (count + 1) + "] " + "Time interval " + fortimerinterval / 1000 + " seconds");
                                        count++;
                                        Thread.Sleep(fortimerinterval);
                                    }
                                    else
                                    {
                                        bool allDone = true;
                                        foreach (var workerThread in workerThreads)
                                        {
                                            if (workerThread.IsAlive)
                                            {
                                                allDone = false;
                                                break;
                                            }
                                        }
                                        if (allDone)
                                        {
                                            Thread.Sleep(15000);
                                            Environment.Exit(0);
                                        }
                                    }
                                }
                            };

                            await client.AddRequestAsync(request);
                            await client.SendAsync();
                        }
                        catch (DicomAssociationRejectedException assoRejectEx)
                        {
                            log.Warn("----------------------------------------------------");
                            log.Warn(tNum + "-[" + (count + 1) + "] " + assoRejectEx.Message);
                            log.Warn("----------------------------------------------------");
                        }
                        catch (Exception exception)
                        {
                            log.Error("----------------------------------------------------");
                            log.Error(tNum + "-[" + (count + 1) + "] " + exception.ToString());
                            log.Error("----------------------------------------------------");
                        }
                    }
                }
                                                              ))
                {
                    IsBackground = true,
                    Name         = $"SenderThread #{i}",
                    Priority     = ThreadPriority.AboveNormal
                };
                workerThreads[i].Start();
            }
            //  Await all background threads
            foreach (var workerThread in workerThreads)
            {
                workerThread.Join(600000);      //  10 minutes thread timeout
            }
            SpinWait.SpinUntil(() => false);
        }
示例#43
0
        public void CanBackupToDirectory_MultipleBackups()
        {
            var backupPath = NewDataPath("BackupFolder");

            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "oren"
                    });
                    var periodicBackupSetup = new PeriodicExportSetup
                    {
                        LocalFolderName      = backupPath,
                        IntervalMilliseconds = 25
                    };
                    session.Store(periodicBackupSetup, PeriodicExportSetup.RavenDocumentKey);

                    session.SaveChanges();
                }
                SpinWait.SpinUntil(() =>
                {
                    var jsonDocument = store.DatabaseCommands.Get(PeriodicExportStatus.RavenDocumentKey);
                    if (jsonDocument == null)
                    {
                        return(false);
                    }
                    var periodicBackupStatus = jsonDocument.DataAsJson.JsonDeserialization <PeriodicExportStatus>();
                    return(periodicBackupStatus.LastDocsEtag != Etag.Empty && periodicBackupStatus.LastDocsEtag != null);
                });

                var etagForBackups = store.DatabaseCommands.Get(PeriodicExportStatus.RavenDocumentKey).Etag;
                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "ayende"
                    });
                    session.SaveChanges();
                }
                SpinWait.SpinUntil(() =>
                                   store.DatabaseCommands.Get(PeriodicExportStatus.RavenDocumentKey).Etag != etagForBackups);
            }

            using (var store = NewDocumentStore())
            {
                var dataDumper = new DataDumper(store.SystemDatabase)
                {
                    SmugglerOptions = { Incremental = true }
                };
                dataDumper.ImportData(new SmugglerImportOptions {
                    FromFile = backupPath
                }).Wait();

                using (var session = store.OpenSession())
                {
                    Assert.Equal("oren", session.Load <User>(1).Name);
                    Assert.Equal("ayende", session.Load <User>(2).Name);
                }
            }
            IOExtensions.DeleteDirectory(backupPath);
        }
		private void Test(Func<long> generate, int threadCount, int generatedIdCount)
		{
			var waitingThreadCount = 0;
			var starterGun = new ManualResetEvent(false);

			var results = new long[generatedIdCount];
			var threads = Enumerable.Range(0, threadCount).Select(threadNumber => new Thread(() =>
			{
				// Wait for all threads to be ready
				Interlocked.Increment(ref waitingThreadCount);
				starterGun.WaitOne();

				for (int i = threadNumber; i < generatedIdCount; i += threadCount)
					results[i] = generate();
			})).ToArray();

			foreach (var t in threads)
				t.Start();

			// Wait for all tasks to reach the waiting stage
			var wait = new SpinWait();
			while (waitingThreadCount < threadCount)
				wait.SpinOnce();

			// Start all the threads at the same time
			starterGun.Set();
			foreach (var t in threads)
				t.Join();

			var ids = new HashSet<long>();
			foreach (var value in results)
			{
				if (!ids.Add(value))
				{
					throw new AssertException("Id " + value + " was generated more than once, in indices "
						+ string.Join(", ", results.Select(Tuple.Create<long, int>).Where(x => x.Item1 == value).Select(x => x.Item2)));
				}
			}

			for (long i = 1; i <= GeneratedIdCount; i++)
				Assert.True(ids.Contains(i), "Id " + i + " was not generated.");
		}
示例#45
0
        /// <summary>
        /// 接收CAN总线上的数据
        /// </summary>
        private void DeviceReceive()
        {
            VCI_ERR_INFO pErrInfo = new VCI_ERR_INFO();

            while (true)
            {
                SpinWait.SpinUntil(() => false, 1);//80
                //返回接收缓冲区中尚未被读取的帧数
                UInt32 num = VCI_GetReceiveNum(devType, devIndex, devChannel);
                if (num == 0)
                {
                    continue;
                }
                //分配一次最多接收VCI_GetReceiveNum函数返回值的帧数的数据存储内存空间
                IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (int)num);
                //返回实际读到的帧数,如返回的为0xFFFFFFFF,则读取数据失败,有错误发生。
                UInt32 len = VCI_Receive(devType, devIndex, devChannel, pt, num, -1);
                if (len == 0xFFFFFFFF)
                {
                    VCI_ReadErrInfo(devType, devIndex, devChannel, ref pErrInfo);
                    //释放分配的内存空间
                    Marshal.FreeHGlobal(pt);
                    continue;
                }

                //获取CAN总线上的数据并触发事件
                for (int i = 0; i < len; i++)
                {
                    VCI_CAN_OBJ receData = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ));

                    string _data = String.Empty;
                    byte[] temp  = receData.Data;
                    for (int j = 0; j < receData.DataLen; j++)
                    {
                        _data += String.Format("{0:X2}", temp[j]) + " ";
                    }

                    //将接收的数据添加到table中
                    lock (DataBase)
                    {
                        DataRow _dr = DataBase.NewRow();
                        _dr["dttype"]    = 1;
                        _dr["id"]        = "0x" + string.Format("{0:X}", receData.ID);
                        _dr["direction"] = (string)Application.Current.Resources["teReceive"];
                        _dr["type"]      = receData.ExternFlag == 0 ? (string)Application.Current.Resources["teStandardFrame"] : (string)Application.Current.Resources["teExtendedFrame"];
                        _dr["time"]      = DateTime.Now.ToString("MM/dd HH:mm:ss:ffff");//((double)receData.TimeStamp / 10000).ToString().PadRight(9, '0');
                        _dr["data"]      = _data.Trim();
                        _dr["signal"]    = 0;
                        DataBase.Rows.Add(_dr);
                        if (DataBase.Rows.Count > 1000)
                        {
                            for (int n = 0; n < DataBase.Rows.Count - 1000; n++)
                            {
                                DataBase.Rows.RemoveAt(0);
                            }
                        }
                    }
                }
                Marshal.FreeHGlobal(pt);
            }
        }
        public void TickCountTest()
        {
            int start = Environment.TickCount;

            Assert.True(SpinWait.SpinUntil(() => Environment.TickCount - start > 0, TimeSpan.FromSeconds(1)));
        }
示例#47
0
文件: SpinWait.cs 项目: Indifer/Test
		public static void SpinUntil (Func<bool> condition)
		{
			SpinWait sw = new SpinWait ();
			while (!condition ())
				sw.SpinOnce ();
		}
 public static void AssertIsFalseEventually(Func <bool> condition, TimeSpan?timeout = null)
 {
     timeout = timeout ?? TimeSpan.FromSeconds(10);
     Assert.IsTrue(SpinWait.SpinUntil(() => !condition(), timeout.Value));
 }
示例#49
0
        public async void Play(object sender, EventArgs e)
        {
            ExecuteTimer.Stop();

            //Globals.FailSafe = 1; //Force failsafe

            //Check for failsafe
            if (Globals.PlayerTurn == 0 || Globals.FailSafe == 1 || Globals.PlayerTurn > PlayersAmount.Maximum || PlayersAmount.Value == 0 || Globals.NotEnoughCards == 1)
            {
                GamesAmount.Value = GamesAmount.Minimum;
                DebugBox.Text     = "";

                Status.Text = "Status: Simulation Ended  ---->  Error (either the card distribution is wrong or memory is corrupted) check debug box";

                DebugBox.AppendText("PlayerTurn ----> " + Globals.PlayerTurn + Environment.NewLine);
                if (Globals.FailSafe == 1)
                {
                    DebugBox.AppendText("FailSafe is set to 1 ---> Try using a set seed." + Environment.NewLine);
                }
                if (Globals.PlayerTurn > PlayersAmount.Maximum)
                {
                    DebugBox.AppendText("PlayerTurn > PlayersAmount.Maximum ----> Are you editing memory? Wrong value to edit" + Environment.NewLine);
                }
                if (PlayersAmount.Value == 0)
                {
                    DebugBox.AppendText("PlayersAmount.Value == 0 ----> Are you editing memory? Wrong value to edit" + Environment.NewLine);
                }
                if (Globals.NotEnoughCards == 1)
                {
                    DebugBox.AppendText("Globals.NotEnoughCards ---->  You need to add more cards" + Environment.NewLine);
                }

                DebugBox.AppendText(Environment.NewLine + "Open an issue on my GitHub and paste this output if you don't know how to solve this issue");
            }
            else
            {
                var watch = System.Diagnostics.Stopwatch.StartNew();

                Status.Text = "Status: Running simulation...";
                //var TempPlayerArray[] =



                //Alpha is the id of the game being simulated
                for (int alpha = 1; alpha <= GamesAmount.Value; alpha++)
                {
                    NewGame();
                    //Set game to on
                    Globals.isGameOn = true;

                    //Used to check if player can play or not
                    //var ALLOW_TURN_EDIT = 1;

                    //Display current game in Main
                    CurrentGameLabel.Text = "Current game: " + alpha + "/" + GamesAmount.Value;



                    //While game is on
                    //                           {{{{{{{{     NOTE: THIS IS BASICALLY THE BEGINNING OF THE AI     }}}}}}}}
                    while (Globals.isGameOn)
                    {
                        //Add a tiny-tiny delay
                        await PutTaskDelay(1);

                        //Reset personal flags
                        Globals.DoIHaveSameColors  = false;
                        Globals.DoIHaveSameNumbers = false;
                        Globals.DoIHaveSameID      = false;
                        Globals.DoIHaveWild        = false;

                        //Fix stepping, as it doesn't really work.
                        if (Stepping.Checked)
                        {
                            SpinWait.SpinUntil(() => Globals.DebugWait == false, 50); //This can be used to slow down the calculation
                            if (Globals.DebugWait == false)
                            {
                                Globals.DebugWait = true;
                                Globals.isGameOn  = false;
                            }
                        }


                        /*
                         *
                         * We should consider a setting up a risk score first, then choose what to play based on that
                         *
                         * But before that, check who's playing next.
                         *
                         *
                         */



                        //                                 {{{{{{{{     EVALUATION     }}}}}}}}



                        //                                 {{{{{{{{     WHO'S NEXT ?     }}}}}}}}
                        JObject rss  = JObject.Parse(Globals.JsonGame);
                        JObject game = rss["Game"] as JObject;

                        //Who's playing next?
                        // Json: Game --> Next_Player
                        Globals.PlayerTurn = (int)rss["Game"]["Next_Player"];

                        if (Globals.Clockwise == true)
                        {
                            if (Globals.PlayerTurn + 1 > PlayersAmount.Value)
                            {
                                game["Next_Player"] = 1;
                                Globals.PlayerTurn  = 1;
                            }
                            else
                            {
                                game["Next_Player"] = Globals.PlayerTurn + 1;
                                Globals.PlayerTurn  = Globals.PlayerTurn + 1;
                            }
                        }
                        else
                        {
                            if (Globals.PlayerTurn - 1 == 0)
                            {
                                game["Next_Player"] = PlayersAmount.Value;
                                Globals.PlayerTurn  = Convert.ToInt32(PlayersAmount.Value);
                            }
                            else
                            {
                                game["Next_Player"] = Globals.PlayerTurn - 1;
                                Globals.PlayerTurn  = Globals.PlayerTurn - 1;
                            }
                        }


                        //                                 {{{{{{{{     GET TOP CARD     }}}}}}}}
                        //Get top card

                        Scoreboard.Text = Globals.JsonGame; //debug

                        Globals.DoIHaveSameColors = false;
                        Globals.DoIHaveSameID     = false;

                        //Get identity of deck (current player turn)
                        JArray decks = (JArray)game["Player_Decks"][Globals.PlayerTurn.ToString()];

                        //Check if I have the same color
                        string color_to_check = (string)rss["Game"]["TopCard_Color"];
                        for (int i = 0; i < decks.Count; i++)
                        {
                            if (Globals.DoIHaveSameColors == false && color_to_check == decks[i].ToString().Split('_').Last())
                            {
                                //Set top card color
                                //Top should be: 0_Green
                                //Seed 0 -->  Deck: Contains 1_Green. so it's true (last is 9_blue)

                                Globals.DoIHaveSameColors = true;

                                //Scoreboard.Text = "Top: "+color_to_check+ ",   my: "+decks[i].ToString().Split('_').Last(); //debug
                            }
                        }


                        //Check if I have the same id
                        //It can be a number, trap, wild, ecc.. Same card ignoring color
                        string id_to_check = (string)rss["Game"]["TopCard_ID"];
                        for (int i = 0; i < decks.Count; i++)
                        {
                            if (Globals.DoIHaveSameID == false && id_to_check == decks[i].ToString().Split('_').First())
                            {
                                if (decks[i].ToString().Split('_').First() == "Wild")
                                {
                                    Globals.DoIHaveWild = true;
                                }
                                Globals.DoIHaveSameID = true;
                            }
                        }



                        /* Calculate end game
                         *
                         * -We can check if any player has no cards, that means someone has won
                         *      Better add this check after a placement/usage of card and then we set a flag or simply set "isGameOn" to true
                         *
                         */



                        //Atm I have no idea if the turn change works, as there's nothing that checks if a game must go on.
                        //Once code gets executed here, game just ends (thinking of including a score check for "isGameOn")

                        //Change turn

                        //End of game
                        if (Stepping.Checked == false)
                        {
                            Globals.isGameOn = false;
                        }
                    }
                }
                Status.Text = "Status: Simulation Ended";

                // the code that you want to measure comes here
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                EmulationLabel.Text = "Emulation time taken: " + elapsedMs.ToString() + "ms";
            }

            //END OF SIMULATION
        }
        private void RegularUpdateRealTimeCarInfo(IMaintainDevice mtx, AVEHICLE carOurVh)
        {
            do
            {
                UInt16 car_id      = (ushort)carOurVh.Num;
                UInt16 action_mode = 0;
                if (carOurVh.ACT_STATUS == ProtocolFormat.OHTMessage.VHActionStatus.Commanding)
                {
                    if (!SCUtility.isEmpty(carOurVh.MCS_CMD))
                    {
                        action_mode = CAR_ACTION_MODE_ACTION_FOR_MCS_COMMAND;
                    }
                    else
                    {
                        action_mode = CAR_ACTION_MODE_ACTION;
                    }
                }
                else
                {
                    action_mode = CAR_ACTION_MODE_NO_ACTION;
                }
                UInt16 cst_exist          = (ushort)carOurVh.HAS_CST;
                UInt16 current_section_id = 0;
                UInt16.TryParse(carOurVh.CUR_SEC_ID, out current_section_id);
                UInt16 current_address_id = 0;
                UInt16.TryParse(carOurVh.CUR_ADR_ID, out current_address_id);
                UInt32 buffer_distance = 0;
                UInt16 speed           = (ushort)carOurVh.Speed;

                mtx.CurrentPreCarOurID         = car_id;
                mtx.CurrentPreCarOurActionMode = action_mode;
                mtx.CurrentPreCarOurCSTExist   = cst_exist;
                mtx.CurrentPreCarOurSectionID  = current_section_id;
                mtx.CurrentPreCarOurAddressID  = current_address_id;
                mtx.CurrentPreCarOurDistance   = buffer_distance;
                mtx.CurrentPreCarOurSpeed      = speed;

                mtx.setCarRealTimeInfo(car_id, action_mode, cst_exist, current_section_id, current_address_id, buffer_distance, speed);

                //如果在移動過程中,MTx突然變成手動模式的話,則要將原本在移動的車子取消命令
                if (mtx.MTxMode == MTxMode.Manual || !mtx.CarOutSafetyCheck)
                {
                    carOutRequestCancle(mtx, true);
                    LogHelper.Log(logger: logger, LogLevel: LogLevel.Warn, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                                  Data: $"Device:{mtx.DeviceID} mtx mode suddenly turned mode:{mtx.MTxMode} or car out safety check change:{mtx.CarOutSafetyCheck}, " +
                                  $"so urgent cancel vh:{mtx.PreCarOutVhID} of command.",
                                  XID: mtx.DeviceID);
                    break;
                }
                //如果是MTL的話,要去檢查他的Doking device(MTS)是否狀態有變化,有的話也要將命令給取消
                if (mtx is MaintainLift)
                {
                    IMaintainDevice dokingMaintainDevice = (mtx as MaintainLift).DokingMaintainDevice;
                    if (dokingMaintainDevice != null)
                    {
                        if (!SCUtility.isMatche(dokingMaintainDevice.DeviceSegment, carOurVh.CUR_SEG_ID) &&
                            (dokingMaintainDevice.MTxMode == MTxMode.Manual || !dokingMaintainDevice.CarOutSafetyCheck))
                        {
                            carOutRequestCancle(mtx, true);
                            LogHelper.Log(logger: logger, LogLevel: LogLevel.Warn, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                                          Data: $"Device:{dokingMaintainDevice.DeviceID} of mtx mode suddenly turned mode:{dokingMaintainDevice.MTxMode} or car out safety check change:{dokingMaintainDevice.CarOutSafetyCheck}, " +
                                          $"so urgent cancel vh:{mtx.PreCarOutVhID} of command.",
                                          XID: dokingMaintainDevice.DeviceID);
                            break;
                        }
                    }
                }

                SpinWait.SpinUntil(() => false, 200);
            } while (!mtx.CancelCarOutRequest && !mtx.CarOurSuccess);

            //mtx.setCarRealTimeInfo(0, 0, 0, 0, 0, 0, 0);
        }
        public async Task restore_settings_tests()
        {
            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore(new Options
            {
                ModifyDatabaseName = s => $"{s}_2"
            }))
            {
                var restoreConfiguration = new RestoreBackupConfiguration();

                var restoreBackupTask = new RestoreBackupOperation(restoreConfiguration);
                var e = Assert.Throws <RavenException>(() => store.Maintenance.Server.Send(restoreBackupTask));
                Assert.Contains("Database name can't be null or empty", e.InnerException.Message);

                restoreConfiguration.DatabaseName = store.Database;
                restoreBackupTask = new RestoreBackupOperation(restoreConfiguration);
                e = Assert.Throws <RavenException>(() => store.Maintenance.Server.Send(restoreBackupTask));
                Assert.Contains("Cannot restore data to an existing database", e.InnerException.Message);

                restoreConfiguration.DatabaseName = "test";
                restoreBackupTask = new RestoreBackupOperation(restoreConfiguration);
                e = Assert.Throws <RavenException>(() => store.Maintenance.Server.Send(restoreBackupTask));
                Assert.Contains("Backup location can't be null or empty", e.InnerException.Message);

                restoreConfiguration.BackupLocation = "this-path-doesn't-exist\\";
                restoreBackupTask = new RestoreBackupOperation(restoreConfiguration);
                e = Assert.Throws <RavenException>(() => store.Maintenance.Server.Send(restoreBackupTask));
                Assert.Contains("Backup location doesn't exist", e.InnerException.Message);

                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(new User { Name = "oren" }, "users/1");

                    await session.SaveChangesAsync();
                }

                var config = new PeriodicBackupConfiguration
                {
                    BackupType    = BackupType.Backup,
                    LocalSettings = new LocalSettings
                    {
                        FolderPath = backupPath
                    },
                    IncrementalBackupFrequency = "* * * * *" //every minute
                };

                var backupTaskId = (await store.Maintenance.SendAsync(new UpdatePeriodicBackupOperation(config))).TaskId;
                await store.Maintenance.SendAsync(new StartBackupOperation(true, backupTaskId));

                var operation = new GetPeriodicBackupStatusOperation(backupTaskId);
                SpinWait.SpinUntil(() =>
                {
                    var getPeriodicBackupResult = store.Maintenance.Send(operation);
                    return(getPeriodicBackupResult.Status?.LastEtag > 0);
                }, TimeSpan.FromSeconds(15));

                restoreConfiguration.BackupLocation = backupPath;
                restoreConfiguration.DataDirectory  = backupPath;
                restoreBackupTask = new RestoreBackupOperation(restoreConfiguration);
                e = Assert.Throws <RavenException>(() => store.Maintenance.Server.Send(restoreBackupTask));
                Assert.Contains("New data directory must be empty of any files or folders", e.InnerException.Message);

                var emptyFolder = NewDataPath(suffix: "BackupFolderRestore");
                restoreConfiguration.BackupLocation = backupPath;
                restoreConfiguration.DataDirectory  = emptyFolder;
            }
        }
        public void processCarInScenario(MaintainSpace mts)
        {
            CarInStart(mts);
            //在收到MTL的 Car in safety check後,就可以叫Vh移動至Car in 的buffer區(MTL Home)
            //不過要先判斷vh是否已經在Auto模式下如果是則先將它變成AutoLocal的模式
            if (!SpinWait.SpinUntil(() => mts.CarInSafetyCheck && mts.MTxMode == MTxMode.Auto, 10000))
            {
                LogHelper.Log(logger: logger, LogLevel: LogLevel.Warn, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                              Data: $"mts:{mts.DeviceID}, status not ready CarInSafetyCheck:{mts.CarInSafetyCheck},Mode:{mts.MTxMode} ,can't excute car in",
                              XID: mts.DeviceID);
                CarInFinish(mts);
                return;
            }

            //在車子要Car In的時候,要判斷MTS的前門是否已經開啟
            if (!SpinWait.SpinUntil(() => mts.MTSFrontDoorStatus == MTSDoorStatus.Open, MTS_DOOR_OPEN_TIME_OUT_ms))
            {
                LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                              Data: $"mts:{mts.DeviceID}, status not ready {nameof(mts.MTSFrontDoorStatus)}:{ mts.MTSFrontDoorStatus} ,can't excute car in",
                              XID: mts.DeviceID);
                CarInFinish(mts);
                return;
            }

            AVEHICLE car_in_vh = vehicleBLL.cache.getVhByAddressID(mts.MTS_ADDRESS);

            //if (car_in_vh != null && car_in_vh.isTcpIpConnect)
            if (car_in_vh != null)
            {
                if (car_in_vh.isTcpIpConnect)
                {
                    if (car_in_vh.MODE_STATUS == ProtocolFormat.OHTMessage.VHModeStatus.Manual)
                    {
                        VehicleService.ModeChangeRequest(car_in_vh.VEHICLE_ID, ProtocolFormat.OHTMessage.OperatingVHMode.OperatingAuto);

                        if (SpinWait.SpinUntil(() => car_in_vh.MODE_STATUS == VHModeStatus.AutoMts, 10000))
                        {
                            //mts.SetCarInMoving(true);
                            VehicleService.doAskVhToSystemInAddress(car_in_vh.VEHICLE_ID, mts.MTS_SYSTEM_IN_ADDRESS);
                        }
                        else
                        {
                            LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                                          Data: $"Process car in scenario:{mts.DeviceID} fail. ask vh change to auto mode time out",
                                          XID: mts.DeviceID,
                                          VehicleID: car_in_vh.VEHICLE_ID);
                            CarInFinish(mts);
                        }
                    }
                    else if (car_in_vh.MODE_STATUS == ProtocolFormat.OHTMessage.VHModeStatus.AutoMts)
                    {
                        //mts.SetCarInMoving(true);
                        VehicleService.doAskVhToSystemInAddress(car_in_vh.VEHICLE_ID, mts.MTS_SYSTEM_IN_ADDRESS);
                    }
                }
                else
                {
                    LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                                  Data: $"Process car in scenario fail, mts:{mts.DeviceID}. because on mts of vh:{car_in_vh.VEHICLE_ID} is disconnect ",
                                  XID: mts.DeviceID,
                                  VehicleID: car_in_vh.VEHICLE_ID);
                    //mts.SetCarInMoving(false);
                    CarInFinish(mts);
                }
            }
            else
            {
                LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLService), Device: SCAppConstants.DeviceName.DEVICE_NAME_MTx,
                              Data: $"Process car in scenario fail, mts:{mts.DeviceID}. because no vh in mts",
                              XID: mts.DeviceID);
                //mts.SetCarInMoving(false);
                CarInFinish(mts);
            }
        }
        internal bool AtomicLoopStateUpdate(int newState, int illegalStates, ref int oldState)
        {
            SpinWait sw = new SpinWait();

            do
            {
                oldState = m_LoopStateFlags;
                if ((oldState & illegalStates) != 0) return false;
                if (Interlocked.CompareExchange(ref m_LoopStateFlags, oldState | newState, oldState) == oldState)
                {
                    return true;
                }
                sw.SpinOnce();
            } while (true);

        }
示例#54
0
        private void CheckTrackNotesWithOutputDevice(
            ICollection <EventToSend> eventsToSend,
            ICollection <EventToSend> eventsWillBeSent,
            TimeSpan moveFrom,
            TimeSpan moveTo,
            IEnumerable <int> notesWillBeStarted,
            IEnumerable <int> notesWillBeFinished)
        {
            var playbackContext = new PlaybackContext();

            var receivedEvents = playbackContext.ReceivedEvents;
            var sentEvents     = playbackContext.SentEvents;
            var stopwatch      = playbackContext.Stopwatch;
            var tempoMap       = playbackContext.TempoMap;

            var eventsForPlayback = GetEventsForPlayback(eventsToSend, tempoMap);

            var notes         = eventsForPlayback.GetNotes().ToArray();
            var notesStarted  = new List <Note>();
            var notesFinished = new List <Note>();

            using (var outputDevice = OutputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
            {
                SendReceiveUtilities.WarmUpDevice(outputDevice);
                outputDevice.EventSent += (_, e) => sentEvents.Add(new SentEvent(e.Event, stopwatch.Elapsed));

                using (var playback = new Playback(eventsForPlayback, tempoMap, outputDevice))
                {
                    playback.TrackNotes             = true;
                    playback.NotesPlaybackStarted  += (_, e) => notesStarted.AddRange(e.Notes);
                    playback.NotesPlaybackFinished += (_, e) => notesFinished.AddRange(e.Notes);

                    using (var inputDevice = InputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
                    {
                        inputDevice.EventReceived += (_, e) =>
                        {
                            lock (playbackContext.ReceivedEventsLockObject)
                            {
                                receivedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));
                            }
                        };
                        inputDevice.StartEventsListening();
                        stopwatch.Start();
                        playback.Start();

                        SpinWait.SpinUntil(() => stopwatch.Elapsed >= moveFrom);
                        playback.MoveToTime((MetricTimeSpan)moveTo);

                        var timeout           = TimeSpan.FromTicks(eventsWillBeSent.Sum(e => e.Delay.Ticks)) + SendReceiveUtilities.MaximumEventSendReceiveDelay;
                        var areEventsReceived = SpinWait.SpinUntil(() => receivedEvents.Count == eventsWillBeSent.Count, timeout);
                        Assert.IsTrue(areEventsReceived, $"Events are not received for timeout {timeout}.");

                        stopwatch.Stop();

                        var playbackStopped = SpinWait.SpinUntil(() => !playback.IsRunning, SendReceiveUtilities.MaximumEventSendReceiveDelay);
                        Assert.IsTrue(playbackStopped, "Playback is running after completed.");
                    }
                }
            }

            CompareSentReceivedEvents(sentEvents, receivedEvents, eventsWillBeSent.ToList());

            MidiAsserts.AreEqual(notesStarted, notesWillBeStarted.Select(i => notes[i]), "Invalid notes started.");
            MidiAsserts.AreEqual(notesFinished, notesWillBeFinished.Select(i => notes[i]), "Invalid notes finished.");
        }
示例#55
0
        protected virtual void Dispose(bool disposing) {
            if (!disposed.TryRelaxedSet())
                return;

            if (handle != null) {
                ManualResetEvent tmpHandle = Interlocked.Exchange(ref handle, null);
                if (used > 0) {
                    // A tiny wait (just a few cycles normally) before releasing
                    var wait = new SpinWait();
                    while (used > 0)
                        wait.SpinOnce();
                }
                tmpHandle.Close();
            }
        }
示例#56
0
        private void CheckPlaybackStop(
            ICollection <EventToSend> eventsToSend,
            ICollection <EventToSend> eventsWillBeSent,
            TimeSpan stopAfter,
            TimeSpan stopPeriod,
            PlaybackAction setupPlayback,
            PlaybackAction afterStart,
            PlaybackAction afterStop,
            PlaybackAction afterResume,
            IEnumerable <Tuple <TimeSpan, PlaybackAction> > runningAfterResume = null,
            ICollection <TimeSpan> explicitExpectedTimes = null,
            double speed = 1.0,
            ICollection <ReceivedEvent> expectedReceivedEvents = null,
            ICollection <ReceivedEvent> expectedPlayedEvents   = null)
        {
            var playbackContext = new PlaybackContext();

            var playedEvents   = new List <ReceivedEvent>();
            var receivedEvents = playbackContext.ReceivedEvents;
            var sentEvents     = playbackContext.SentEvents;
            var stopwatch      = playbackContext.Stopwatch;
            var tempoMap       = playbackContext.TempoMap;

            var eventsForPlayback = GetEventsForPlayback(eventsToSend, tempoMap);
            var expectedTimes     = playbackContext.ExpectedTimes;

            if (explicitExpectedTimes != null || expectedReceivedEvents != null || expectedPlayedEvents != null)
            {
                expectedTimes.AddRange(explicitExpectedTimes ?? (expectedReceivedEvents?.Select(e => e.Time) ?? expectedPlayedEvents.Select(e => e.Time)));
            }
            else
            {
                var currentTime = TimeSpan.Zero;

                foreach (var eventWillBeSent in eventsWillBeSent)
                {
                    currentTime += eventWillBeSent.Delay;
                    var scaledCurrentTime = ScaleTimeSpan(currentTime, 1.0 / speed);
                    expectedTimes.Add(currentTime > stopAfter ? scaledCurrentTime + stopPeriod : scaledCurrentTime);
                }
            }

            using (var outputDevice = OutputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
            {
                SendReceiveUtilities.WarmUpDevice(outputDevice);
                outputDevice.EventSent += (_, e) => sentEvents.Add(new SentEvent(e.Event, stopwatch.Elapsed));

                using (var playback = new Playback(eventsForPlayback, tempoMap, outputDevice))
                {
                    playback.Speed = speed;
                    setupPlayback(playbackContext, playback);

                    if (expectedPlayedEvents != null)
                    {
                        playback.EventPlayed += (_, e) => playedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));
                    }

                    using (var inputDevice = InputDevice.GetByName(SendReceiveUtilities.DeviceToTestOnName))
                    {
                        inputDevice.EventReceived += (_, e) =>
                        {
                            lock (playbackContext.ReceivedEventsLockObject)
                            {
                                receivedEvents.Add(new ReceivedEvent(e.Event, stopwatch.Elapsed));
                            }
                        };
                        inputDevice.StartEventsListening();
                        stopwatch.Start();
                        playback.Start();

                        afterStart(playbackContext, playback);

                        SpinWait.SpinUntil(() => stopwatch.Elapsed >= stopAfter);
                        playback.Stop();

                        afterStop(playbackContext, playback);

                        Thread.Sleep(stopPeriod);
                        playback.Start();

                        afterResume(playbackContext, playback);

                        if (runningAfterResume != null)
                        {
                            foreach (var check in runningAfterResume)
                            {
                                Thread.Sleep(check.Item1);
                                check.Item2(playbackContext, playback);
                            }
                        }

                        var timeout           = expectedTimes.Last() + SendReceiveUtilities.MaximumEventSendReceiveDelay;
                        var areEventsReceived = SpinWait.SpinUntil(() => receivedEvents.Count == expectedTimes.Count, timeout);
                        Assert.IsTrue(areEventsReceived, $"Events are not received for timeout {timeout}.");

                        stopwatch.Stop();

                        var playbackStopped = SpinWait.SpinUntil(() => !playback.IsRunning, SendReceiveUtilities.MaximumEventSendReceiveDelay);
                        Assert.IsTrue(playbackStopped, "Playback is running after completed.");
                    }
                }
            }

            CompareSentReceivedEvents(sentEvents, receivedEvents, expectedTimes);

            if (expectedReceivedEvents != null)
            {
                CompareReceivedEvents(receivedEvents, expectedReceivedEvents.ToList());
            }

            if (expectedPlayedEvents != null)
            {
                CompareReceivedEvents(playedEvents, expectedPlayedEvents.ToList());
            }
        }
示例#57
0
文件: SpinOnce.cs 项目: Nucs/nlib
        /// <summary>
        ///     Spins until the specified condition is satisfied or until the specified timeout is expired.
        /// </summary>
        /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
        /// <param name="millisecondsTimeout">
        ///     The number of milliseconds to wait, or
        ///     <see
        ///         cref="System.Threading.Timeout.Infinite" />
        ///     (-1) to wait indefinitely.
        /// </param>
        /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="condition" /> argument is null.</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        ///     <paramref name="millisecondsTimeout" /> is a
        ///     negative number other than -1, which represents an infinite time-out.
        /// </exception>
        public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout) {
            if (millisecondsTimeout < Timeout.Infinite) {
                throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, "SpinWait_SpinUntil_TimeoutWrong");
            }
            if (condition == null) {
                throw new ArgumentNullException("condition", "SpinWait_SpinUntil_ArgumentNull");
            }
            long startTicks = 0;
            ;
            if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite) {
                startTicks = DateTime.UtcNow.Ticks;
            }
            var spinner = new SpinWait();
            while (!condition()) {
                if (millisecondsTimeout == 0) {
                    return false;
                }

                spinner.SpinOnce();

                if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield) {
                    if (millisecondsTimeout <= (DateTime.UtcNow.Ticks - startTicks)/TimeSpan.TicksPerMillisecond) {
                        return false;
                    }
                }
            }
            return true;
        }
        public async Task GrpcOpenCensusInputTests_StopsAndRestarts()
        {
            // ARRANGE
            int batchesReceived = 0;
            ExportTraceServiceRequest receivedBatch = null;

            int port  = GetPort();
            var input = new GrpcOpenCensusInput("localhost", port);

            input.Start(
                (exportSpanRequest, callContext) =>
            {
                batchesReceived++;
                receivedBatch = exportSpanRequest;
            },
                (configRequest, callContext) => ConfigResponse);

            Assert.IsTrue(SpinWait.SpinUntil(() => input.IsRunning, GrpcOpenCensusInputTests.DefaultTimeout));

            var grpcWriter = new GrpcWriter(false, port);

            ExportTraceServiceRequest batch = new ExportTraceServiceRequest();

            batch.Spans.Add(new Span()
            {
                Name = new TruncatableString()
                {
                    Value = "Event1"
                }
            });

            await grpcWriter.Write(batch).ConfigureAwait(false);

            Common.AssertIsTrueEventually(
                () => input.GetStats().BatchesReceived == 1 && batchesReceived == 1 &&
                receivedBatch.Spans.Single().Name.Value == "Event1", GrpcOpenCensusInputTests.DefaultTimeout);

            // ACT
            input.Stop();

            Common.AssertIsTrueEventually(
                () => !input.IsRunning && input.GetStats().BatchesReceived == 1 && batchesReceived == 1 &&
                receivedBatch.Spans.Single().Name.Value == "Event1", GrpcOpenCensusInputTests.DefaultTimeout);

            input.Start(
                (exportSpanRequest, callContext) =>
            {
                batchesReceived++;
                receivedBatch = exportSpanRequest;
            },
                (configRequest, callContext) => ConfigResponse);

            Assert.IsTrue(SpinWait.SpinUntil(() => input.IsRunning, GrpcOpenCensusInputTests.DefaultTimeout));

            grpcWriter = new GrpcWriter(false, port);
            batch.Spans.Single().Name.Value = "Event2";
            await grpcWriter.Write(batch).ConfigureAwait(false);

            // ASSERT
            Common.AssertIsTrueEventually(
                () => input.IsRunning && input.GetStats().BatchesReceived == 1 && batchesReceived == 2 &&
                receivedBatch.Spans.Single().Name.Value == "Event2", GrpcOpenCensusInputTests.DefaultTimeout);
        }
 public static void AssertIsFalseEventually(Func <bool> condition, TimeSpan?timeout = null)
 {
     timeout = timeout ?? Timeout.InfiniteTimeSpan;
     Assert.IsFalse(SpinWait.SpinUntil(condition, timeout.Value));
 }
示例#60
0
        public void Authenticate_should_not_throw_when_authentication_succeeds(
            [Values(false, true)] bool async)
        {
            var randomStringGenerator = new ConstantRandomStringGenerator(_clientNonce);
            var subject = new ScramSha256Authenticator(__credential, randomStringGenerator);

            var saslStartReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                @"{conversationId: 1," +
                                                                                $" payload: BinData(0,\"{ToUtf8Base64(_serverResponse1)}\")," +
                                                                                @" done: false, 
                   ok: 1}"));
            var saslContinueReply = MessageHelper.BuildReply <RawBsonDocument>(RawBsonDocumentHelper.FromJson(
                                                                                   @"{conversationId: 1," +
                                                                                   $" payload: BinData(0,\"{ToUtf8Base64(_serverReponse2)}\")," +
                                                                                   @" done: true, 
                   ok: 1}"));

            var connection = new MockConnection(__serverId);

            connection.EnqueueReplyMessage(saslStartReply);
            connection.EnqueueReplyMessage(saslContinueReply);

            var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1;

            Action act;

            if (async)
            {
                act = () => subject.AuthenticateAsync(connection, __description, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                act = () => subject.Authenticate(connection, __description, CancellationToken.None);
            }

            var exception = Record.Exception(act);

            exception.Should().BeNull();
            SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue();

            var sentMessages = MessageHelper.TranslateMessagesToBsonDocuments(connection.GetSentMessages());

            sentMessages.Count.Should().Be(2);

            var actualRequestId0 = sentMessages[0]["requestId"].AsInt32;
            var actualRequestId1 = sentMessages[1]["requestId"].AsInt32;

            actualRequestId0.Should().BeInRange(expectedRequestId, expectedRequestId + 10);
            actualRequestId1.Should().BeInRange(actualRequestId0 + 1, actualRequestId0 + 11);

            sentMessages[0].Should().Be(
                @"{opcode: ""query""," +
                $" requestId: {actualRequestId0}," +
                @" database: ""source"", 
                   collection: ""$cmd"", 
                   batchSize: -1, 
                   slaveOk: true, 
                   query: {saslStart: 1, 
                           mechanism: ""SCRAM-SHA-256""," +
                $"         payload: new BinData(0, \"{ToUtf8Base64(_clientRequest1)}\")}}}}");
            sentMessages[1].Should().Be(
                @"{opcode: ""query""," +
                $" requestId: {actualRequestId1}," +
                @" database: ""source"", 
                   collection: ""$cmd"", 
                   batchSize: -1, 
                   slaveOk: true, 
                   query: {saslContinue: 1, 
                           conversationId: 1, " +
                $"         payload: new BinData(0, \"{ToUtf8Base64(_clientRequest2)}\")}}}}");
        }