コード例 #1
0
 private void Handle(SystemMessage.BecomeMaster msg)
 {
     lock (_lock){
         _roleAssignments.Add("master");
     }
     _expectedNumberOfEvents?.Signal();
 }
コード例 #2
0
 public override IMessage BeforeHandled(IMessage message, IMessageChannel channel, IMessageHandler handler)
 {
     Assert.NotNull(message);
     Counter++;
     latch?.Signal();
     return(MessageToReturn ?? message);
 }
コード例 #3
0
        // Validates init, set, reset state transitions.
        private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce)
        {
            CountdownEvent ev = new CountdownEvent(initCount);

            Assert.Equal(initCount, ev.InitialCount);

            // Increment (optionally).
            for (int i = 1; i < increms + 1; i++)
            {
                ev.AddCount();
                Assert.Equal(initCount + i, ev.CurrentCount);
            }

            // Decrement until it hits 0.
            if (takeAllAtOnce)
            {
                ev.Signal(initCount + increms);
            }
            else
            {
                for (int i = 0; i < initCount + increms; i++)
                {
                    Assert.False(ev.IsSet, string.Format("  > error: latch is set after {0} signals", i));
                    ev.Signal();
                }
            }

            Assert.True(ev.IsSet);
            Assert.Equal(0, ev.CurrentCount);

            // Now reset the event and check its count.
            ev.Reset();
            Assert.Equal(ev.InitialCount, ev.CurrentCount);
        }
コード例 #4
0
        public void TestAdd()
        {
            var item = new KeyValuePair <string, string>("1", "value");
            var observableDictionary = PerformObservableDictionarySetup(new List <KeyValuePair <string, string> >());

            var latch = new CountdownEvent(4);

            var collectionChangedActions = new List <NotifyCollectionChangedAction>();
            var propertiesChanged        = new List <string>();

            void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args)
            {
                collectionChangedActions.Add(args.Action);
                latch?.Signal();
            }

            void PropertyChangedHandler(object sender, PropertyChangedEventArgs args)
            {
                propertiesChanged.Add(args.PropertyName);
                latch?.Signal();
            }

            observableDictionary.CollectionChanged += CollectionChangedHandler;
            observableDictionary.PropertyChanged   += PropertyChangedHandler;

            observableDictionary.Add(item.Key, item.Value);

            latch.Wait();

            Assert.Single(observableDictionary);

            var keys = new string[1];

            observableDictionary.Keys.CopyTo(keys, 0);
            Assert.Equal("1", keys[0]);

            var values = new string[1];

            observableDictionary.Values.CopyTo(values, 0);
            Assert.Equal("value", values[0]);

            Assert.Single(collectionChangedActions);
            Assert.Equal(NotifyCollectionChangedAction.Add, collectionChangedActions[0]);

            Assert.Equal(3, propertiesChanged.Count);
            Assert.Contains("Count", propertiesChanged);
            Assert.Contains("Keys", propertiesChanged);
            Assert.Contains("Values", propertiesChanged);

            latch.Dispose();
        }
コード例 #5
0
        public void TestTryAdd()
        {
            var latch = new CountdownEvent(4);

            var collectionChangedActions = new List <NotifyCollectionChangedAction>();
            var propertiesChanged        = new List <string>();

            void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args)
            {
                collectionChangedActions.Add(args.Action);
                latch?.Signal();
            }

            void PropertyChangedHandler(object sender, PropertyChangedEventArgs args)
            {
                propertiesChanged.Add(args.PropertyName);
                latch?.Signal();
            }

            var observableDictionary =
                new ObservableConcurrentDictionary <string, string>(CollectionChangedHandler, PropertyChangedHandler);

            var success = observableDictionary.TryAdd("1", "value");

            latch.Wait();

            Assert.True(success);

            Assert.Single(observableDictionary);

            var keys = new string[1];

            observableDictionary.Keys.CopyTo(keys, 0);
            Assert.Equal("1", keys[0]);

            var values = new string[1];

            observableDictionary.Values.CopyTo(values, 0);
            Assert.Equal("value", values[0]);

            Assert.Single(collectionChangedActions);
            Assert.Equal(NotifyCollectionChangedAction.Add, collectionChangedActions[0]);

            Assert.Equal(3, propertiesChanged.Count);
            Assert.Contains("Count", propertiesChanged);
            Assert.Contains("Keys", propertiesChanged);
            Assert.Contains("Values", propertiesChanged);

            latch.Dispose();
        }
コード例 #6
0
        private void Handle(SystemMessage.StateChangeMessage msg)
        {
            switch (msg.State)
            {
            case Data.VNodeState.Master:
                _expectedNumberOfRoleAssignments?.Signal();
                _epochIds.Add(((SystemMessage.BecomeMaster)msg).EpochId);
                break;

            case Data.VNodeState.Slave:
                _expectedNumberOfRoleAssignments?.Signal();
                _epochIds.Add(((SystemMessage.BecomeSlave)msg).EpochId);
                break;
            }
        }
コード例 #7
0
        /// <summary>
        /// Starts disposal. If disposal has been deferred, disposal will not start
        /// until the deferral tokens have been released.
        /// </summary>
        public async ValueTask DisposeAsync()
        {
            lock (this)
            {
                if (!IsAsyncDisposeRequested)
                {
                    IsAsyncDisposeRequested = true;
                    _countdown?.Signal();
                }
            }

            await WaitAsync();

            Dispose(true);
        }
コード例 #8
0
ファイル: ControlsLayout.cs プロジェクト: dotsetup/dotsetup
        public void PrepareResources(CountdownEvent onReady)
        {
            ResourcesReady = false;
            CountdownEvent preparingResources = new CountdownEvent(_controlSettings.Count);

            foreach (KeyValuePair <string, ControlSettings> kvp in _controlSettings)
            {
                kvp.Value.PrepareResources(preparingResources);
            }
            ;

            _preparingResourcesThread = new Thread(() =>
            {
                preparingResources.Wait();
                preparingResources.Dispose();
                ResourcesReady = true;
                foreach (KeyValuePair <string, ControlSettings> kvp in _controlSettings)
                {
#if DEBUG
                    Logger.GetLogger().Info($"{kvp.Key} control settings are " + (kvp.Value.IsReady ? "ready" : "not ready"), Logger.Level.MEDIUM_DEBUG_LEVEL);
#endif
                    ResourcesReady &= kvp.Value.IsReady;
                }
                ;
                onReady?.Signal();
            })
            {
                IsBackground = true
            };
            _preparingResourcesThread.Start();
        }
        /// <summary>Initializes the IOCompletionPortTaskScheduler.</summary>
        /// <param name="maxConcurrencyLevel">The maximum number of threads in the scheduler to be executing concurrently.</param>
        /// <param name="numAvailableThreads">The number of threads to have available in the scheduler for executing tasks.</param>
        public IOCompletionPortTaskScheduler(int maxConcurrencyLevel, int numAvailableThreads)
        {
            // Validate arguments
            if (maxConcurrencyLevel < 1) throw new ArgumentNullException("maxConcurrencyLevel");
            if (numAvailableThreads < 1) throw new ArgumentNullException("numAvailableThreads");

            m_tasks = new ConcurrentQueue<Task>();
            m_iocp = new IOCompletionPort(maxConcurrencyLevel);
            m_schedulerThread = new ThreadLocal<bool>();
            m_remainingThreadsToShutdown = new CountdownEvent(numAvailableThreads);

            // Create and start the threads
            for (int i = 0; i < numAvailableThreads; i++)
            {
                new Thread(() =>
                {
                    try
                    {
                        // Note that this is a scheduler thread.  Used for inlining checks.
                        m_schedulerThread.Value = true;

                        // Continually wait on the I/O completion port until 
                        // there's a work item, then process it.
                        while (m_iocp.WaitOne())
                        {
                            Task next;
                            if (m_tasks.TryDequeue(out next)) TryExecuteTask(next);
                        }
                    }
                    finally { m_remainingThreadsToShutdown.Signal(); }
                }) { IsBackground = true }.Start();
            }
        }
コード例 #10
0
        [I] public void ReturnsExpectedResponse()
        {
            Exception      ex              = null;
            CountdownEvent observableWait  = null;
            var            reindexRoutines = new List <Action>
            {
                () => ReindexMany(GetSignal, Signal),
                () => ReindexSingleType(GetSignal, Signal),
                () => ReindexProjection(GetSignal, Signal)
            };

            observableWait = new CountdownEvent(reindexRoutines.Count);
            foreach (var a in reindexRoutines)
            {
                a();
            }

            observableWait.Wait(TimeSpan.FromMinutes(3));
            if (ex != null)
            {
                throw ex;
            }

            void Signal(Exception e)
            {
                ex = e;
                // ReSharper disable once AccessToModifiedClosure
                observableWait?.Signal();
            }

            // ReSharper disable once AccessToModifiedClosure
            CountdownEvent GetSignal() => observableWait;
        }
コード例 #11
0
 private void RemoveFirstMatcher()
 {
     lock (matchersLock)
     {
         matchers.RemoveFirst();
         matchersCompletedLatch?.Signal();
     }
 }
コード例 #12
0
        public void TestAddOrUpdateToAdd()
        {
            var item    = new KeyValuePair <string, string>("1", "value");
            var newItem = new KeyValuePair <string, string>("2", "newValue");
            var observableDictionary = PerformObservableDictionarySetup(new List <KeyValuePair <string, string> > {
                item
            });

            var latch = new CountdownEvent(4);

            var collectionChangedActions = new List <NotifyCollectionChangedAction>();
            var propertiesChanged        = new List <string>();

            void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args)
            {
                collectionChangedActions.Add(args.Action);
                latch?.Signal();
            }

            void PropertyChangedHandler(object sender, PropertyChangedEventArgs args)
            {
                propertiesChanged.Add(args.PropertyName);
                latch?.Signal();
            }

            observableDictionary.CollectionChanged += CollectionChangedHandler;
            observableDictionary.PropertyChanged   += PropertyChangedHandler;

            observableDictionary.AddOrUpdate(newItem.Key, newItem.Value);

            latch.Wait();

            Assert.Equal(2, observableDictionary.Count);
            Assert.Equal(newItem.Value, observableDictionary[newItem.Key]);

            Assert.Single(collectionChangedActions);
            Assert.Equal(NotifyCollectionChangedAction.Add, collectionChangedActions[0]);

            Assert.Equal(3, propertiesChanged.Count);
            Assert.Contains("Count", propertiesChanged);
            Assert.Contains("Keys", propertiesChanged);
            Assert.Contains("Values", propertiesChanged);
        }
コード例 #13
0
        public void TestRemoveWithKeyValuePair()
        {
            var item = new KeyValuePair <string, string>("1", "value");
            var observableDictionary = PerformObservableDictionarySetup(new List <KeyValuePair <string, string> > {
                item
            });

            var latch = new CountdownEvent(4);

            var collectionChangedActions = new List <NotifyCollectionChangedAction>();
            var propertiesChanged        = new List <string>();

            void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs args)
            {
                collectionChangedActions.Add(args.Action);
                latch?.Signal();
            }

            void PropertyChangedHandler(object sender, PropertyChangedEventArgs args)
            {
                propertiesChanged.Add(args.PropertyName);
                latch?.Signal();
            }

            observableDictionary.CollectionChanged += CollectionChangedHandler;
            observableDictionary.PropertyChanged   += PropertyChangedHandler;

            var success = observableDictionary.Remove(item);

            latch.Wait();

            Assert.True(success);

            Assert.Empty(observableDictionary);

            Assert.Single(collectionChangedActions);
            Assert.Equal(NotifyCollectionChangedAction.Remove, collectionChangedActions[0]);

            Assert.Equal(3, propertiesChanged.Count);
            Assert.Contains("Count", propertiesChanged);
            Assert.Contains("Keys", propertiesChanged);
            Assert.Contains("Values", propertiesChanged);
        }
コード例 #14
0
 public void Execute()
 {
     if (_count.Value-- > 0)
     {
         _pool.UnsafeQueueUserWorkItem(this, true);
     }
     else
     {
         _signal?.Signal();
     }
 }
コード例 #15
0
 public static bool SignalBy(this CountdownEvent thisValue, int count)
 {
     if (count < 0)
     {
         throw new ArgumentOutOfRangeException(nameof(count));
     }
     if (count == 0)
     {
         return(thisValue?.CurrentCount == 0);
     }
     return(thisValue?.CurrentCount == 0 || thisValue?.Signal(count.NotAbove(thisValue.CurrentCount)) == true);
 }
コード例 #16
0
        /// <summary>
        /// Download specified download group.
        /// </summary>
        /// <param name="groupName">The download group name.</param>
        /// <returns></returns>
        /// <exception cref="ClickOnceException">
        /// An exception occurred during version update.
        /// </exception>
        /// <exception cref="OperationCanceledException">
        /// Version update was canceled.
        /// </exception>
        public async Task <bool> DownloadFileGroupAsync(string groupName)
        {
            CountdownEvent countdown = null;
            bool           result    = false;

            void progress(object sender, DeploymentProgressChangedEventArgs e)
            {
                Notifier.Progress(new ClickOnceProgressInfo(e));
            }

            void completed(object sender, AsyncCompletedEventArgs e)
            {
                Notifier.Complete();

                if (e.Error != null)
                {
                    throw new ClickOnceException(string.Format("An exception occurred while updating the version of group '{0}'. {1}", groupName, e.Error.Message), e.Error);
                }

                if (e.Cancelled)
                {
                    throw new OperationCanceledException("Version update was canceled.");
                }

                result = true;

                countdown?.Signal();
            }

            try
            {
                ApplicationDeployment.CurrentDeployment.DownloadFileGroupProgressChanged += progress;
                ApplicationDeployment.CurrentDeployment.DownloadFileGroupCompleted       += completed;

                Notifier.Start();

                countdown = new CountdownEvent(1);

                await Task.Run(() => ApplicationDeployment.CurrentDeployment.DownloadFileGroupAsync(groupName)).ConfigureAwait(false);

                countdown.Wait();
            }
            finally
            {
                ApplicationDeployment.CurrentDeployment.DownloadFileGroupProgressChanged -= progress;
                ApplicationDeployment.CurrentDeployment.DownloadFileGroupCompleted       -= completed;

                countdown?.Dispose();
            }

            return(result);
        }
コード例 #17
0
        public static void RunPartitionerStaticTest_SingleChunking()
        {
            CountdownEvent cde = new CountdownEvent(2);
            Action[] actions = new Action[256];

            // The thinking here is that we'll put enough "filler" into this array to
            // insure that "natural" chunk size is greater than 2.  Without the
            // NoBuffering option, the Parallel.ForEach below is certain to deadlock.
            // Somewhere a Signal() is going to be after a Wait() in the same chunk, and
            // the loop will deadlock.
            for (int i = 0; i < 252; i++) actions[i] = () => { };
            actions[252] = () => { cde.Wait(); };
            actions[253] = () => { cde.Signal(); };
            actions[254] = () => { cde.Wait(); };
            actions[255] = () => { cde.Signal(); };

            Debug.WriteLine("    * We'll hang here if EnumerablePartitionerOptions.NoBuffering is not working properly");
            Parallel.ForEach(Partitioner.Create(actions, EnumerablePartitionerOptions.NoBuffering), item =>
            {
                item();
            });
        }
コード例 #18
0
        /// <summary>
        /// Update application version.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ClickOnceException">
        /// An exception occurred during version update.
        /// </exception>
        /// <exception cref="OperationCanceledException">
        /// Version update was canceled.
        /// </exception>
        public async Task <bool> UpdateAsync()
        {
            CountdownEvent countdown = null;
            bool           result    = false;

            void progress(object sender, DeploymentProgressChangedEventArgs e)
            {
                Notifier.Progress(new ClickOnceProgressInfo(e));
            }

            void completed(object sender, AsyncCompletedEventArgs e)
            {
                Notifier.Complete();

                if (e.Error != null)
                {
                    throw new ClickOnceException("An exception occurred during version update. " + e.Error.Message, e.Error);
                }

                if (e.Cancelled)
                {
                    throw new OperationCanceledException("Version update was canceled.");
                }

                result = true;
                countdown?.Signal();
            }

            try
            {
                ApplicationDeployment.CurrentDeployment.UpdateProgressChanged += progress;
                ApplicationDeployment.CurrentDeployment.UpdateCompleted       += completed;

                Notifier.Start();

                countdown = new CountdownEvent(1);

                await Task.Run(() => ApplicationDeployment.CurrentDeployment.UpdateAsync()).ConfigureAwait(false);

                countdown.Wait();
            }
            finally
            {
                ApplicationDeployment.CurrentDeployment.UpdateProgressChanged -= progress;
                ApplicationDeployment.CurrentDeployment.UpdateCompleted       -= completed;

                countdown?.Dispose();
            }

            return(result);
        }
コード例 #19
0
        public void DispatchEvent(LogEvent actualLogEvent)
        {
            Visitor[] visitors = null;
            if (actualLogEvent.Params.ContainsKey("visitors"))
            {
                JArray jArray = (JArray)actualLogEvent.Params["visitors"];
                visitors = jArray.ToObject <Visitor[]>();
            }

            if (visitors == null)
            {
                return;
            }

            foreach (var visitor in visitors)
            {
                foreach (var snapshot in visitor.Snapshots)
                {
                    var decisions = snapshot.Decisions ?? new Decision[1] {
                        new Decision()
                    };
                    foreach (var decision in decisions)
                    {
                        foreach (var @event in snapshot.Events)
                        {
                            var userAttributes = new UserAttributes();
                            foreach (var attribute in visitor.Attributes.Where(attr => !attr.Key.StartsWith(DatafileProjectConfig.RESERVED_ATTRIBUTE_PREFIX)))
                            {
                                userAttributes.Add(attribute.Key, attribute.Value);
                            }

                            ActualEvents.Add(new CanonicalEvent(decision.ExperimentId, decision.VariationId, @event.Key,
                                                                visitor.VisitorId, userAttributes, @event.EventTags));
                        }
                    }
                }
            }

            try
            {
                CountdownEvent?.Signal();
            }
            catch (ObjectDisposedException)
            {
                Logger.Log(LogLevel.ERROR, "The CountdownEvent instance has already been disposed.");
            }
            catch (InvalidOperationException)
            {
                Logger.Log(LogLevel.ERROR, "The CountdownEvent instance has already been set.");
            }
        }
コード例 #20
0
        //#客制化更新
        private static void AutoUpdater_CheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args != null)
            {
                //#是否有新版本
                if (args.IsUpdateAvailable)
                {
                    DialogResult dialogResult;

                    dialogResult =
                        MessageBox.Show(
                            $"現在有新的版本 {args.CurrentVersion}。\n"
                            + $"你目前的版本為 {args.InstalledVersion}。\n"
                            + $"你要現在更新版本嗎?",
                            "有新的版本了",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information);
                    //#要更新版本
                    if (dialogResult == DialogResult.Yes)
                    {
                        try
                        {
                            //#如果有需要釋放的資源要先釋放
                            disposableObj?.Dispose();
                            //#下載新版
                            //#檔案不存在時會顯示錯誤對話盒, 但不用有Exception
                            if (AutoUpdater.DownloadUpdate())
                            {
                                //#Console要改用Environment而不是Application
                                Application.Exit();
                                //Environment.Exit(0);
                            }
                        }
                        catch (Exception exception) //#有寫有保佑
                        {
                            MessageBox.Show(exception.Message, exception.GetType().ToString(), MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else //#連不到
            {
                MessageBox.Show(
                    @"無法連線更新伺服器,繼續使用目前版本。",
                    @"檢查更新", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //#計數減1後為0則釋放執行緒
            countdownEvent?.Signal();
        }
コード例 #21
0
        private void OnTransportMessageReceived(TransportMessage transportMessage)
        {
            if (transportMessage.MessageTypeId == MessageTypeId.PersistenceStoppingAck)
            {
                _logger.InfoFormat("Received PersistenceStoppingAck from {0}", transportMessage.Originator.SenderId);
                _ackCountdown?.Signal();
                return;
            }

            if (transportMessage.MessageTypeId.IsInfrastructure())
            {
                MessageReceived?.Invoke(transportMessage);
            }
            else
            {
                _pendingReceives.TryAdd(transportMessage);
            }
        }
コード例 #22
0
        private async void RunConcurrentTaskAsync(long taskId, Task task)
        {
            Interlocked.Increment(ref activeTaskCount);

            try
            {
                taskStatus.TryAdd(taskId, false);
                await task.ConfigureAwait(false);

                Interlocked.Increment(ref finishedTaskCount);
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref failedTaskCount);

                if (OnError != null)
                {
                    TaskExceptionEventArgs eventArgs = new TaskExceptionEventArgs(ex);

                    try
                    {
                        OnError(this, eventArgs);
                    }
                    catch (Exception devException)
                    {
                        Debug.Fail(devException.Message);
                    }
                }
            }
            finally
            {
                taskStatus.TryUpdate(taskId, true, false);
            }

            Interlocked.Decrement(ref activeTaskCount);

            if (!disposed)
            {
                taskCounter?.Signal();
                RunRemainingTask();
            }
        }
コード例 #23
0
            public static IWorkerTask Task(string id, SemaphoreSlim blockSignal = null, CountdownEvent startSignal = null, CountdownEvent finishSignal = null, Action action = null, bool disposeBlock = false)
            {
                IDisposable resources = null;

                if (disposeBlock)
                {
                    resources = blockSignal;
                }

                return(new DelegateWorkerTask(
                           id,
                           () =>
                {
                    startSignal?.Signal();

                    blockSignal?.Wait();

                    action?.Invoke();

                    finishSignal?.Signal();
                },
                           resources));
            }
コード例 #24
0
ファイル: SftpSession.cs プロジェクト: InoMurko/win-sshfs
        /// <summary>
        /// Performs SSH_FXP_WRITE request.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="data">The data to send.</param>
        /// <param name="wait">The wait event handle if needed.</param>
        public void RequestWrite(byte[] handle, UInt64 offset, byte[] data)
        {
            const int maximumDataSize = 1024 * 32 - 38;

            if (data.Length < maximumDataSize + 1)
            {
                using (var wait = new AutoResetEvent(false))
                {
                    var request = new SftpWriteRequest(this.NextRequestId, handle, offset, data,
                                                       (response) =>
                                                           {
                                                               if (response.StatusCode == StatusCodes.Ok)
                                                               {
                                                                   wait.Set();
                                                               }
                                                               else
                                                               {
                                                                   ThrowSftpException(response);
                                                               }
                                                           });

                    this.SendRequest(request);

                   
                    this.WaitHandle(wait, this._operationTimeout);
                }

            }
            else
            {
              
            int block = ((data.Length - 1)/maximumDataSize) + 1;
            using (var cnt = new CountdownEvent(block))
            {
                for (int i = 0; i < block; i++)
                {
                    var blockBufferSize = Math.Min(data.Length - maximumDataSize*i, maximumDataSize);
                    var blockBuffer = new byte[blockBufferSize];

                    Buffer.BlockCopy(data, i*maximumDataSize, blockBuffer, 0, blockBufferSize);

                    var request = new SftpWriteRequest(this.NextRequestId, handle, offset + (ulong) (i*maximumDataSize),
                                                       blockBuffer,
                                                       (response) =>
                                                           {
                                                               if (response.StatusCode == StatusCodes.Ok)
                                                               {
                                                                   // if (wait != null)
                                                                   //  wait.Set();
                                                                   cnt.Signal();
                                                               }
                                                               else
                                                               {
                                                                   ThrowSftpException(response);
                                                               }
                                                           });

                    this.SendRequest(request);
                }

                this.WaitHandle(cnt.WaitHandle, this._operationTimeout/*new TimeSpan(block*this._operationTimeout.Ticks)*/);
                

            }
            }
        }
コード例 #25
0
        public static ParallelTaskResult StaticFor(int low, int high,
            Action<ParallelTaskOptions, int, int> work, int workerCount, int chunk)
        {
            if (low < 0 || high < low) return new ParallelTaskResult();

            ModuleProc PROC = new ModuleProc("ParallelTasks", "StaticFor");
            ParallelTaskResult result = new ParallelTaskResult(ParallelTaskResultStatus.Created);
            if (workerCount <= 0) workerCount = 1;
            if (chunk <= 0) chunk = 1;
            if (high < chunk) chunk = ((high - low) / workerCount);

            CountdownEvent cde = new CountdownEvent(workerCount);
            Thread[] threads = new Thread[workerCount];
            int currentCount = 0;
            ParallelTaskOptions options = new ParallelTaskOptions();

            try
            {
                for (int i = 0; i < workerCount; i++)
                {
                    threads[i] = Extensions.CreateThreadAndStart((o) =>
                    {
                        int k = (int)o;
                        int start = low + (k * chunk);
                        int end = ((k == (workerCount - 1)) ? high : (start + chunk));

                        for (int j = start; j < end; j++)
                        {
                            if (options.IsCancelled) break;

                            try
                            {
                                work(options, j, currentCount);
                            }
                            catch (Exception ex)
                            {
                                Log.Exception(PROC, ex);
                                result.Exceptions.Add(ex);
                            }
                            finally
                            {
                                Interlocked.Increment(ref currentCount);
                            }
                        }

                        cde.Signal();
                    }, i, "StaticFor_" + i.ToString());
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
            finally
            {
                cde.Wait();
                result.Status = (options.IsCancelled ? ParallelTaskResultStatus.Canceled : ParallelTaskResultStatus.Completed);
            }

            return result;
        }
コード例 #26
0
        public static ParallelTaskResult DynamicFor(int low, int high,
            Action<ParallelTaskOptions, int, int> work, int workerCount)
        {
            if (low < 0 || high < low) return new ParallelTaskResult();

            ModuleProc PROC = new ModuleProc("ParallelTasks", "For");
            ParallelTaskResult result = new ParallelTaskResult(ParallelTaskResultStatus.Created);
            if (workerCount <= 0) workerCount = 1;
            const int chunk = 16;

            CountdownEvent cde = new CountdownEvent(workerCount);
            Thread[] threads = new Thread[workerCount];
            int currentCount = 0;
            int currentValue = low;
            ParallelTaskOptions options = new ParallelTaskOptions();

            try
            {
                for (int i = 0; i < workerCount; i++)
                {
                    threads[i] = Extensions.CreateThreadAndStart((o) =>
                    {
                        int j = 0;
                        int currentChunk = 1;

                        while (true)
                        {
                            if (options.IsCancelled) break;
                            if ((currentValue + currentChunk) > Int32.MaxValue) break;
                            j = Interlocked.Add(ref currentValue, currentChunk) - currentChunk;
                            if (j >= high) break;

                            for (int k = 0; (k < currentChunk) && ((j + k) < high); k++)
                            {
                                if (options.IsCancelled) break;

                                try
                                {
                                    work(options, j, currentCount);
                                }
                                catch (Exception ex)
                                {
                                    Log.Exception(PROC, ex);
                                }
                                finally
                                {
                                    Interlocked.Increment(ref currentCount);
                                }
                            }
                            if (currentChunk < chunk) currentChunk *= 2;
                        }

                        cde.Signal();
                    }, i);
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
            finally
            {
                cde.Wait();
                result.Status = (options.IsCancelled ? ParallelTaskResultStatus.Canceled : ParallelTaskResultStatus.Completed);
            }

            return result;
        }
コード例 #27
0
        public void StopTest_MultiplyWaiters()
        {
            var target = CreateFixedThreadPool(2, false);
            var heavyTask = new TaskMock(Wait);
            Assert.AreEqual(true, target.Execute(heavyTask, Priority.High));
            Assert.AreEqual(true, target.Execute(heavyTask, Priority.Medium));
            Assert.AreEqual(true, target.Execute(heavyTask, Priority.Low));
            Assert.AreEqual(true, target.Execute(heavyTask, Priority.Low));

            Exception deferedException = null;
            var waitersCounter = new CountdownEvent(4);

            for (var i = 0; i < 4; i++)
            {
                new Thread(() =>
                {
                    target.Stop();
                    try
                    { // each thread should see properly stopped pool.
                        AssertIsProperlyStopped(target);
                    }
                    catch (Exception e)
                    {
                        deferedException = e;
                    }
                    waitersCounter.Signal();
                }).Start();
            }

            target.Stop();
            AssertIsProperlyStopped(target);

            waitersCounter.Wait(); // if thread pool works properly, will never blocked here

            if (deferedException != null)
            {
                throw deferedException;
            }
        }
コード例 #28
0
ファイル: EtwTests.cs プロジェクト: SGuyGe/corefx
        public void TestEtw()
        {
            using (var listener = new TestEventListener(new Guid("16F53577-E41D-43D4-B47E-C17025BF4025"), EventLevel.Verbose))
            {
                ActionBlock<int> ab = null;
                BufferBlock<int> bb = null;
                int remaining = 0;
                CountdownEvent ce = new CountdownEvent(0);

                // Check that block creation events fire
                const int DataflowBlockCreatedId = 1;
                remaining = 2;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: DataflowBlockCreatedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        ab = new ActionBlock<int>(i => { });
                        bb = new BufferBlock<int>(); // trigger block creation event
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that linking events fire
                const int BlockLinkedId = 4;
                remaining = 1;
                IDisposable link = null;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockLinkedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        link = bb.LinkTo(ab);
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that unlinking events fire
                const int BlockUnlinkedId = 5;
                remaining = 1;
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockUnlinkedId, actual: ev.EventId);
                        remaining--;
                    },
                    () => {
                        link.Dispose();
                        Assert.Equal(expected: 0, actual: remaining);
                    });

                // Check that task launched events fire
                const int TaskLaunchedId = 2;
                ce.Reset(1);
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: TaskLaunchedId, actual: ev.EventId);
                        ce.Signal();
                    },
                    () => {
                        ab.Post(42);
                        ce.Wait();
                        Assert.Equal(expected: 0, actual: ce.CurrentCount);
                    });

                // Check that completion events fire
                const int BlockCompletedId = 3;
                ce.Reset(2);
                listener.RunWithCallback(ev => {
                        Assert.Equal(expected: BlockCompletedId, actual: ev.EventId);
                        ce.Signal();
                    },
                    () => {
                        ab.Complete();
                        bb.Complete();
                        ce.Wait();
                        Assert.Equal(expected: 0, actual: ce.CurrentCount);
                    });

            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: xxxxxyyyy/wmiServSessEnum
        static void Main(string[] args)
        {
            Thread th = Thread.CurrentThread;

            th.Name = "MainThread";
            var           comparer = StringComparer.OrdinalIgnoreCase;
            var           arguments = new Dictionary <string, string>(comparer);
            CimCredential Credentials = null;
            int           maxThreads = 10;
            int           timeout = 10;
            int           workers, async;
            String        mode = "all";
            //we create a DComSessionOptions object to force our remote connections to use DCom instead of WinRM
            DComSessionOptions SessionOptions = new DComSessionOptions();

            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                {
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                }
                if (argument.ToLower() == "help" || argument.ToLower() == "-h")
                {
                    help();
                    System.Environment.Exit(0);
                }
            }

            List <String> targetHosts = new List <string>();

            Console.WriteLine("");
            //gather targets, either from file or directly from commandline
            if (arguments.ContainsKey("-l"))
            {
                targetHosts = arguments["-l"].Split(',').ToList();
                if (arguments.ContainsKey("-f"))
                {
                    Console.WriteLine("Error -- please only use one targeting flag at a time (-l or -f)");
                    System.Environment.Exit(1);
                }
            }
            else if (arguments.ContainsKey("-f"))
            {
                try
                {
                    targetHosts = File.ReadAllLines(arguments["-f"]).ToList();
                }
                catch
                {
                    Console.WriteLine($"Error - the input file at {arguments["-f"]} could not be read");
                    System.Environment.Exit(2);
                }
            }
            else
            {
                Console.WriteLine("Error -- please to enter systems to target\n");
                help();
                Environment.Exit(1);
            }
            if (arguments.ContainsKey("-m"))
            {
                try
                {
                    mode = System.Enum.Parse(typeof(Modules), arguments["-m"], true).ToString();
                }
                catch
                {
                    Console.WriteLine("Error -- invalid collection mode selected");
                    System.Environment.Exit(1);
                }
            }
            if ((arguments.ContainsKey("-d")) || (arguments.ContainsKey("-u")) || (arguments.ContainsKey("-p")))
            {
                try
                {
                    SecureString securepassword = new SecureString();
                    foreach (char c in arguments["-p"])
                    {
                        securepassword.AppendChar(c);
                    }
                    Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, arguments["-d"], arguments["-u"], securepassword);
                }
                catch
                {
                    Console.WriteLine("Error -- if using alternative credentials, please ensure to include domain, username, and password (use a domain of . for a local account)");
                    System.Environment.Exit(1);
                }
            }

            //get available worker threads, we dont care about async.
            ThreadPool.GetAvailableThreads(out workers, out async);
            if (arguments.ContainsKey("-t"))
            {
                if (System.Convert.ToInt32(arguments["-t"]) <= workers)
                {
                    maxThreads = System.Convert.ToInt32(arguments["-t"]);
                }
                else
                {
                    Console.WriteLine("Error - not enough available worker threads in the .net thread pool (max available = " + workers + ")");
                    System.Environment.Exit(1);
                }
            }
            Console.WriteLine(workers + " worker threads available, will use up to " + maxThreads + " threads");
            ThreadPool.SetMaxThreads(maxThreads, 1);

            //wait / timeout value for wmi connects
            if (arguments.ContainsKey("-w"))
            {
                timeout = System.Convert.ToInt32(arguments["-w"]);
            }
            TimeSpan interval = new TimeSpan(0, 0, timeout);

            SessionOptions.Timeout = interval;

            // if using CimCredential with creds not inherited from current session, we'll add to our session options
            if (Credentials != null)
            {
                SessionOptions.AddDestinationCredentials(Credentials);
            }

            Console.WriteLine("Starting collection on " + targetHosts.Count + " host(s)");
            var count = new CountdownEvent(targetHosts.Count);

            foreach (string s in targetHosts)
            {
                ThreadPool.QueueUserWorkItem(status => { wmiConnect(s, SessionOptions, mode); count.Signal(); });
            }
            count.Wait();

            Console.WriteLine("----------Collection completed, results should be displayed above----------");
        }
コード例 #30
0
            public override void Run()
            {
                DirectoryReader currentReader = null;
                Random          random        = LuceneTestCase.Random;

                try
                {
                    Document doc = new Document();
                    doc.Add(new TextField("id", "1", Field.Store.NO));
                    Writer.AddDocument(doc);
                    Holder.Reader = currentReader = Writer.GetReader(true);
                    Term term = new Term("id");
                    for (int i = 0; i < NumOps && !Holder.Stop; i++)
                    {
                        float nextOp = (float)random.NextDouble();
                        if (nextOp < 0.3)
                        {
                            term.Set("id", new BytesRef("1"));
                            Writer.UpdateDocument(term, doc);
                        }
                        else if (nextOp < 0.5)
                        {
                            Writer.AddDocument(doc);
                        }
                        else
                        {
                            term.Set("id", new BytesRef("1"));
                            Writer.DeleteDocuments(term);
                        }
                        if (Holder.Reader != currentReader)
                        {
                            Holder.Reader = currentReader;
                            if (Countdown)
                            {
                                Countdown = false;
                                Latch.Signal();
                            }
                        }
                        if (random.NextBoolean())
                        {
                            Writer.Commit();
                            DirectoryReader newReader = DirectoryReader.OpenIfChanged(currentReader);
                            if (newReader != null)
                            {
                                currentReader.DecRef();
                                currentReader = newReader;
                            }
                            if (currentReader.NumDocs == 0)
                            {
                                Writer.AddDocument(doc);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Failed = e;
                }
                finally
                {
                    Holder.Reader = null;
                    if (Countdown)
                    {
                        Latch.Signal();
                    }
                    if (currentReader != null)
                    {
                        try
                        {
                            currentReader.DecRef();
                        }
#pragma warning disable 168
                        catch (IOException e)
#pragma warning restore 168
                        {
                        }
                    }
                }
                if (VERBOSE)
                {
                    Console.WriteLine("writer stopped - forced by reader: " + Holder.Stop);
                }
            }
コード例 #31
0
        private static Task Convert(List <ConvertApiFileParam> fileParams, ConvConfig cfg, List <BlockingCollection <ConvertApiFileParam> > outQueues)
        {
            var fileNamesStr = string.Join(", ", fileParams.Select(f => f.GetValueAsync().Result.FileName).ToList());
            // Console.WriteLine($"Converting: {fileNamesStr} -> {cfg.DestinationFormat}");
            var orderedFileParams = fileParams.OrderBy(fp => fp.GetValueAsync().Result.FileName).ToList();
            var srcFormat         = orderedFileParams.First().GetValueAsync().Result.FileExt;
            var convertParams     = orderedFileParams.Cast <ConvertApiBaseParam>().Concat(cfg.Params).ToList();

            Cde?.AddCount();
            _concSem.Wait();

            return(_convertApi.ConvertAsync(srcFormat, cfg.DestinationFormat, convertParams)
                   .ContinueWith(tr =>
            {
                _concSem.Release();
                if (tr.IsCompletedSuccessfully)
                {
                    try
                    {
                        tr.Result.Files.ToList().ForEach(resFile =>
                        {
                            if (outQueues.Any())
                            {
                                var fp = new ConvertApiFileParam(resFile.Url);
                                outQueues.ForEach(action: q => q.Add(fp));
                                Cde?.Signal();
                            }

                            if (!outQueues.Any() || cfg.SaveIntermediate)
                            {
                                resFile.SaveFileAsync(Path.Join(cfg.Directory.FullName, resFile.FileName))
                                .ContinueWith(tfi =>
                                {
                                    Console.WriteLine(tfi.Result.FullName);
                                    Cde?.Signal();
                                    if (Cde?.CurrentCount == 1)
                                    {
                                        Cde?.Signal();                                    // Removing initial count to unblock wait
                                    }
                                });
                            }
                        });
                    }
                    catch (ConvertApiException e)
                    {
                        Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{e.Message}\n{e.Response}");
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{e.Message}");
                    }
                }
                else
                {
                    Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{tr.Exception?.Flatten().Message}");
                    Cde?.Signal();
                    if (Cde?.CurrentCount == 1)
                    {
                        Cde?.Signal();                                // Removing initial count to unblock wait
                    }
                }
            }));
        }
コード例 #32
0
ファイル: TaskTest.cs プロジェクト: xiaochuwang/mono
        public void WaitAny_ManyExceptions()
        {
            CountdownEvent cde   = new CountdownEvent(3);
            var            tasks = new [] {
                Task.Factory.StartNew(delegate { try { throw new ApplicationException(); } finally { cde.Signal(); } }),
                Task.Factory.StartNew(delegate { try { throw new ApplicationException(); } finally { cde.Signal(); } }),
                Task.Factory.StartNew(delegate { try { throw new ApplicationException(); } finally { cde.Signal(); } })
            };

            Assert.IsTrue(cde.Wait(1000), "#1");

            try {
                Assert.IsTrue(Task.WaitAll(tasks, 1000), "#2");
            } catch (AggregateException e) {
                Assert.AreEqual(3, e.InnerExceptions.Count, "#3");
            }
        }
コード例 #33
0
        public void TestRecoverAfterDeletedQueueAndLostConnection()
        {
            var connectionFactory = new Mock <IConnectionFactory>();
            var connection        = new Mock <IConnection>();
            var channel           = new Mock <RC.IModel>();

            connectionFactory.Setup((f) => f.CreateConnection()).Returns(connection.Object);
            connection.Setup(c => c.CreateChannel(It.IsAny <bool>())).Returns(channel.Object);
            connection.Setup(c => c.IsOpen).Returns(true);
            channel.Setup(c => c.IsOpen).Returns(true);
            var n = new AtomicInteger();
            var consumerCaptor = new AtomicReference <RC.IBasicConsumer>();
            var consumerLatch  = new CountdownEvent(2);

            channel.Setup(c => c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()))
            .Callback <string, bool, string, bool, bool, IDictionary <string, object>, RC.IBasicConsumer>((a1, a2, a3, a4, a5, a6, a7) =>
            {
                consumerCaptor.Value = a7;
                consumerLatch.Signal();
            })
            .Returns("consumer" + n.IncrementAndGet());
            channel.Setup(c => c.BasicCancel("consumer2"))
            .Throws(new Exception("Intentional cancel fail"));
            var blockingQueueConsumer = new BlockingQueueConsumer(
                connectionFactory.Object,
                new DefaultMessageHeadersConverter(),
                new ActiveObjectCounter <BlockingQueueConsumer>(),
                AcknowledgeMode.AUTO,
                false,
                1,
                null,
                "testQ1",
                "testQ2");
            var latch = new CountdownEvent(1);

            Task.Run(() =>
            {
                blockingQueueConsumer.Start();
                while (true)
                {
                    try
                    {
                        blockingQueueConsumer.NextMessage(1000);
                    }
                    catch (ConsumerCancelledException)
                    {
                        latch.Signal();
                        break;
                    }
                    catch (ShutdownSignalException)
                    {
                        // Noop
                    }
                    catch (Exception)
                    {
                        // noop
                    }
                }
            });
            Assert.True(consumerLatch.Wait(TimeSpan.FromSeconds(10)));
            var consumer = consumerCaptor.Value;

            consumer.HandleBasicCancel("consumer1");
            Assert.True(latch.Wait(TimeSpan.FromSeconds(10)));
        }
コード例 #34
0
 public void OnComplete()
 {
     cde.Signal();
 }
コード例 #35
0
            //---------------------------------------------------------------------------------------
            // Straightforward IEnumerator<T> methods.
            //

            internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
            {
                Debug.Assert(_source != null);

                if (_alreadySearched)
                {
                    return(false);
                }

                // Look for the greatest element.
                TSource candidate      = default(TSource);
                TKey    candidateKey   = default(TKey);
                bool    candidateFound = false;

                try
                {
                    int     loopCount = 0; //counter to help with cancellation
                    TSource value     = default(TSource);
                    TKey    key       = default(TKey);
                    while (_source.MoveNext(ref value, ref key))
                    {
                        if ((loopCount & CancellationState.POLL_INTERVAL) == 0)
                        {
                            CancellationState.ThrowIfCanceled(_cancellationToken);
                        }

                        // If the predicate is null or the current element satisfies it, we will remember
                        // it as the current partition's candidate for the last element, and move on.
                        if (_predicate == null || _predicate(value))
                        {
                            candidate      = value;
                            candidateKey   = key;
                            candidateFound = true;
                        }

                        loopCount++;
                    }

                    // If we found a candidate element, try to publish it, so long as it's greater.
                    if (candidateFound)
                    {
                        lock (_operatorState)
                        {
                            if (_operatorState._partitionId == -1 || _keyComparer.Compare(candidateKey, _operatorState._key) > 0)
                            {
                                _operatorState._partitionId = _partitionId;
                                _operatorState._key         = candidateKey;
                            }
                        }
                    }
                }
                finally
                {
                    // No matter whether we exit due to an exception or normal completion, we must ensure
                    // that we signal other partitions that we have completed.  Otherwise, we can cause deadlocks.
                    _sharedBarrier.Signal();
                }

                _alreadySearched = true;

                // Only if we have a candidate do we wait.
                if (_partitionId == _operatorState._partitionId)
                {
                    _sharedBarrier.Wait(_cancellationToken);

                    // Now re-read the shared index. If it's the same as ours, we won and return true.
                    if (_operatorState._partitionId == _partitionId)
                    {
                        currentElement = candidate;
                        currentKey     = 0; // 1st (and only) element, so we hardcode the output index to 0.
                        return(true);
                    }
                }

                // If we got here, we didn't win. Return false.
                return(false);
            }
コード例 #36
0
        public static void RunCountdownEventTest2_Exceptions()
        {
            CountdownEvent cde = null;
            Assert.Throws<ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1));
            // Failure Case: Constructor didn't throw AORE when -1 passed

            cde = new CountdownEvent(1);
            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Signal(0));
            // Failure Case: Signal didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws<InvalidOperationException>(() => cde.Signal());
            // Failure Case: Signal didn't throw IOE when the count is zero

            cde = new CountdownEvent(1);
            Assert.Throws<InvalidOperationException>(() => cde.Signal(2));
            // Failure Case: Signal didn't throw IOE when the signal count > current count

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.AddCount(0));
            // Failure Case: AddCount didn't throw AORE when 0 passed

            cde = new CountdownEvent(0);
            Assert.Throws<InvalidOperationException>(() => cde.AddCount(1));
            // Failure Case: AddCount didn't throw IOE when the count is zero

            cde = new CountdownEvent(int.MaxValue - 10);
            Assert.Throws<InvalidOperationException>(() => cde.AddCount(20));
            // Failure Case: AddCount didn't throw IOE when the count > int.Max

            cde = new CountdownEvent(2);
            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Reset(-1));
            // Failure Case: Reset didn't throw AORE when the count is zero

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(-2));
            // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1)));
            // Failure Case:  FAILED.  Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
            // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1

            Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken()));
            // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max

            cde.Dispose();

            Assert.Throws<ObjectDisposedException>(() => cde.Wait());
            // Failure Case: Wait() didn't throw ODE after Dispose
        }
コード例 #37
0
        private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Console.WriteLine("开始接收串口发来的数据");
                int    len = Port.BytesToRead;
                byte[] buf = new byte[len];
                Port.Read(buf, 0, len);
                ByteList.AddRange(buf);
                Console.WriteLine("读到的数据长度" + len);
                #region 测试专用
                if (len == 1)
                {
                    if (ByteList[0] == 0xE0)
                    {
                        SendCmd(new byte[] { 0x55, 0x02, 0x12, 0x34, 0x1f, 0x00, 0x01, 0x00, 0x3a, 0x12, 0xbb });
                    }
                    ByteList.RemoveAt(0);
                }
                #endregion
                #region 对串口数据进行处理
                while (ByteList.Count >= 10)
                {
                    //查找数据标头
                    if (ByteList[0] == 0x55)
                    {
                        if (ByteList[1] == 0x02)
                        {
                            if (ByteList[4] == 0x1f)
                            {
                                int length = ByteList[6] + 10; //数据包长度
                                if (length == 11)              //接收到是的查询命令,不是返回的数据
                                {
                                    ByteList.RemoveRange(0, ByteList.Count);
                                    break;
                                }
                                if (ByteList.Count < length) //数据未接收完毕,跳出循环
                                {
                                    break;
                                }
                                byte[] _data = new byte[length - 3];
                                Array.Copy(ByteList.ToArray(), 0, _data, 0, length - 3);
                                byte[] _dataCrc = _data.Crc();
                                if (_dataCrc[0] == ByteList[length - 3] && _dataCrc[1] == ByteList[length - 2]) //CRC的校验
                                {
                                    buf = new byte[length];
                                    ByteList.CopyTo(0, buf, 0, length);
                                    ByteList.RemoveRange(0, length);
                                    //教室地址
                                    string classroom = Convert.ToString(buf[2], 16) + Convert.ToString(buf[3], 16);
                                    if (DataDictionary.ContainsKey(classroom))
                                    {
                                        Console.WriteLine("有一条未消费的数据,key值为:" + classroom);
                                        DataDictionary.Remove(classroom);
                                    }
                                    Console.WriteLine("一条数据已经添加到字典中,key值为:" + classroom);
                                    DataDictionary.Add(classroom, buf);
                                    countdown.Signal();
                                }
                            }
                            else if (ByteList[4] == 0x07) //表示接收到教室控制器发送过来的报警数据
                            {
                                int length = ByteList[6] + 10;
                                if (ByteList.Count < length) //数据未接收完毕,跳出循环
                                {
                                    break;
                                }
                                byte[] _data = new byte[length - 3];
                                Array.Copy(ByteList.ToArray(), 0, _data, 0, length - 3);
                                byte[] _dataCrc = _data.Crc();
                                if (_dataCrc[0] == ByteList[length - 3] && _dataCrc[1] == ByteList[length - 2]) //CRC的校验
                                {
                                    buf = new byte[length];
                                    ByteList.CopyTo(0, buf, 0, length);
                                    ByteList.RemoveRange(0, length);

                                    AlarmData.Enqueue(buf);
                                }
                            }
                            else //目前不需要的数据
                            {
                                ByteList.RemoveAt(0);
                                ByteList.RemoveAt(0);
                                ByteList.RemoveAt(0);
                                ByteList.RemoveAt(0);
                            }
                        }
                        else
                        {
                            ByteList.RemoveAt(0);
                            ByteList.RemoveAt(0);
                        }
                    }
                    else
                    {
                        ByteList.RemoveAt(0);
                    }
                }
                #endregion
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
コード例 #38
0
        public static void StaticWorkerFor(ParallelTasksStaticWorkerForInput input)
        {
            if (input.TasksLow < 0 || input.TasksHigh < input.TasksLow) return;

            ModuleProc PROC = new ModuleProc("ParallelTasks", "StaticFor");
            if (input.WorkerCount <= 0)
            {
                if (input.Chunk > 0) { input.WorkerCount = (int)Math.Max(Math.Ceiling(Convert.ToDouble(input.TasksHigh) / Convert.ToDouble(input.Chunk)), 1); }
                else { input.WorkerCount = 1; }
            }
            if (input.Chunk <= 0)
            {
                input.Chunk = (input.TasksHigh / input.WorkerCount);
            }
            if (input.Chunk <= 0) input.Chunk = 1;
            if (input.TasksHigh < input.Chunk) input.Chunk = ((input.TasksHigh - input.TasksLow) / input.WorkerCount);

            CountdownEvent cde = new CountdownEvent(input.WorkerCount);
            Thread[] threads = new Thread[input.WorkerCount];
            int currentCount = 0;
            ParallelTaskOptions options = new ParallelTaskOptions();
            WorkerItem item = new WorkerItem()
            {
                ExecutorService = input.Executor,
                Result = new ParallelTaskResult(ParallelTaskResultStatus.Created),
                Completed = input.WorkCompleted,
                EventHandle = cde,
            };

            try
            {
                for (int i = 0; i < input.WorkerCount; i++)
                {
                    threads[i] = Extensions.CreateThreadAndStart((o) =>
                    {
                        int k = (int)o;
                        int start = input.TasksLow + (k * input.Chunk);
                        int end = ((k == (input.WorkerCount - 1)) ? input.TasksHigh : (start + input.Chunk));

                        // work input.Chunk started
                        if (input.WorkChunkStarted != null)
                        {
                            try
                            {
                                input.WorkChunkStarted(new ParallelTaskWorkChunkStartArgs()
                                {
                                    Options = options,
                                    ThreadIndex = i,
                                    ChunkStart = start,
                                    ChunkEnd = end,
                                    SeqStart = 0,
                                    SeqEnd = (end - 1 - start),
                                });
                            }
                            catch (Exception ex)
                            {
                                Log.Exception(PROC, ex);
                                item.Result.Exceptions.Add(ex);
                            }
                        }

                        // work
                        int chunkProgress = start;
                        for (int j = start, sj = 0; j < end; j++, sj++)
                        {
                            if ((input.Executor != null && input.Executor.IsShutdown)
                                || options.IsCancelled) break;
                            chunkProgress = j;

                            try
                            {
                                int proIdx = Interlocked.Increment(ref currentCount);
                                int proPerc = (int)(((float)proIdx / (float)input.TasksHigh) * 100.0);
                                string text = string.Format("{0:D} of {1:D} ({2:D} %)", proIdx, input.TasksHigh, proPerc);
                                input.Work(new ParallelTaskWorkArgs()
                                {
                                    Options = options,
                                    ThreadIndex = k,
                                    ChunkProgress = j,
                                    ChunkSeqProgress = sj,
                                    OverallProgress = proIdx,
                                    Total = input.TasksHigh,
                                    ProgressText = text,
                                });
                            }
                            catch (Exception ex)
                            {
                                Log.Exception(PROC, ex);
                                item.Result.Exceptions.Add(ex);
                            }
                            finally
                            {
                                Interlocked.Increment(ref currentCount);
                            }

                            Thread.Sleep(input.SleepInMilliseconds);
                        }

                        // work input.Chunk completed
                        if (input.WorkChunkCompleted != null)
                        {
                            try
                            {
                                input.WorkChunkCompleted(new ParallelTaskWorkChunkCompletedArgs()
                                {
                                    Options = options,
                                    ThreadIndex = i,
                                    ChunkProgress = chunkProgress,
                                    OverallProgress = currentCount,
                                });
                            }
                            catch (Exception ex)
                            {
                                Log.Exception(PROC, ex);
                                item.Result.Exceptions.Add(ex);
                            }
                        }

                        cde.Signal();
                    }, i, "StaticFor_" + i.ToString() + "_");
                    Thread.Sleep(10);
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
            finally
            {
                Extensions.CreateThreadAndStart((o) =>
                {
                    WorkerItem wi = o as WorkerItem;
                    wi.EventHandle.Wait();
                    wi.Result.Status = (((input.Executor != null && input.Executor.IsShutdown)
                                        || options.IsCancelled) ? ParallelTaskResultStatus.Canceled : ParallelTaskResultStatus.Completed);
                    if (wi.Completed != null)
                    {
                        wi.Completed(new ParallelTaskWorkCompletedArgs()
                        {
                            Result = wi.Result,
                        });
                    }
                }, item, "StaticFor_Wait_");
            }
        }
コード例 #39
0
        public void EventLoop_TimeCollisions()
        {
            var M = 1000;
            var N = 4;

            for (var i = 0; i < N; i++)
            {
                for (var j = 1; j <= M; j *= 10)
                {
                    using (var e = new EventLoopScheduler())
                    {
                        using (var d = new CompositeDisposable())
                        {
                            var cd = new CountdownEvent(j);

                            for (var k = 0; k < j; k++)
                            {
                                d.Add(e.Schedule(TimeSpan.FromMilliseconds(100), () => cd.Signal()));
                            }

                            if (!cd.Wait(10000))
                            {
                                Assert.True(false, "j = " + j);
                            }
                        }
                    }
                }
            }
        }
コード例 #40
0
ファイル: Program.cs プロジェクト: RyanPan/CodeBook
 public void CreateFile(object obj)
 {
     File.WriteAllText(Path.Combine(dir.FullName, string.Format("out\\file{0:0000}.txt", index)), content);
     //Thread.Sleep(100);
     cde.Signal();
 }