Ejemplo n.º 1
0
        /// <summary>
        /// Run a single set of arguments.
        /// </summary>
        public void Run()
        {
            // are there arguments?
            if (_argsSet.Dequeue(out Arguments))
            {
                // yes, run the action
                _lock.Take();
                try {
                    Action.Run();
                } finally {
                    _lock.Release();
                }

                // while there are more arguments
                while (_argsSet.Dequeue(out Arguments))
                {
                    // run the action
                    _lock.Take();
                    try {
                        Action.Run();
                    } finally {
                        _lock.Release();
                    }
                }
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Run a single set of arguments.
 /// </summary>
 public void Run()
 {
     // is there another set of arguments?
     if (_argsSet.Dequeue())
     {
         // run the action
         var action = _action.TakeItem();
         _action.Release();
         action.Run();
         while (_argsSet.Dequeue())
         {
             action.Run();
         }
     }
 }
Ejemplo n.º 3
0
    public void SafeQueue_peek_works()
    {
        var q = new SafeQueue <string>();

        Assert.IsNotNull(q);
        Assert.AreEqual(0, q.Count);
        q.Enqueue("a");
        Assert.AreEqual(1, q.Count);
        var result = q.Peek();

        Assert.AreEqual("a", result);
        result = q.Dequeue();
        Assert.AreEqual("a", result);
        result = q.Dequeue();
        Assert.AreEqual(null, result);
    }
Ejemplo n.º 4
0
 private void Update()
 {
     if ((events != null) && (!events.isEmpty()))
     {
         GameBoardEvent e = events.Dequeue();
         e.doEvent();
     }
 }
Ejemplo n.º 5
0
    public void SafeQueue_isEmpty_works()
    {
        var q = new SafeQueue <string>();

        Assert.IsNotNull(q);
        Assert.AreEqual(0, q.Count);
        Assert.AreEqual(true, q.IsEmpty);
        q.Enqueue("content");
        Assert.AreEqual(false, q.IsEmpty);
        var result2 = q.Dequeue();

        Assert.AreEqual("content", result2);
        Assert.AreEqual(true, q.IsEmpty);
        result2 = q.Dequeue();
        Assert.AreEqual(true, q.IsEmpty);
        Assert.AreEqual(null, result2);
    }
Ejemplo n.º 6
0
 /// <summary>
 /// Run a single set of arguments.
 /// </summary>
 public void Run()
 {
     // is there another set of arguments?
     if (_argsSet.Dequeue())
     {
         // run the action
         Needle.AddSingle(Action);
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        ///Dequeue 的测试
        ///</summary>
        public void DequeueTestHelper <ValueT>()
        {
            SafeQueue <ValueT> target   = new SafeQueue <ValueT>(); // TODO: 初始化为适当的值
            ValueT             expected = default(ValueT);          // TODO: 初始化为适当的值
            ValueT             actual;

            actual = target.Dequeue();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Ejemplo n.º 8
0
 public static void DispatchActionsIfPresent()
 {
     if (IsEnable)
     {
         DispatchAction action = dispatchActions.Dequeue();
         if (!action.Executed)
         {
             action.ExecuteDispatch();
         }
     }
 }
Ejemplo n.º 9
0
 public static void RunActioin()
 {
     if (_actions.Count >= 1)
     {
         Action action = _actions.Dequeue();
         if (action != null)
         {
             action();
         }
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Call run once to complete all tasks.
 /// </summary>
 public void Run()
 {
     _ticker.Push();
     // get run number
     _runCount = _ticker.Ticks - 1;
     // run all tasks
     while (_tasks.Dequeue())
     {
         _tasks.Current.Run();
     }
     _ticker.Pull();
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Allocate an event arg for a send operation
        /// </summary>
        public static SocketAsyncEventArgs AllocateForSend(EventHandler <SocketAsyncEventArgs> ioCompletedHandler)
        {
            SocketAsyncEventArgs result;

            if (!_eventArgsSend.Dequeue(out result))
            {
                result = new SocketAsyncEventArgs();
            }

            result.Completed += ioCompletedHandler;
            return(result);
        }
Ejemplo n.º 12
0
        public void _0001_StructQueueMsg()
        {
            CanMessage msg_1 = new CanMessage();

            msg_1.TwoByte = 0x0001;
            CanMessage msg_2 = new CanMessage();

            msg_2.TwoByte = 0x0002;

            SafeQueue <CanMessage> queue = new SafeQueue <CanMessage>();

            queue.Enqueue(msg_1);
            queue.Enqueue(msg_1);

            CanMessage msg_d1 = queue.Dequeue();

            Assert.AreEqual(msg_1.TwoByte, 0x0001);
            CanMessage msg_d2 = queue.Dequeue();

            Assert.AreEqual(msg_2.TwoByte, 0x0002);
        }
Ejemplo n.º 13
0
    /// <summary>
    /// 解析重要消息
    /// </summary>
    public static void AnalysisImportantCache4RecMsg()
    {
        //需要立即执行的情况
        if (IsNeedImneduately)
        {
            while (Cache4RecMsgQueue.Count > 0)
            {
                //获取第一个消息
                Cache4RecMsg message = Cache4RecMsgQueue.Dequeue();
                //处理消息
                AnalysisCache4RecMsg(message.id, message.content);
            }

            IsNeedImneduately = false;
        }
        //处理异步线程的work
        while (queue.Count > 0)
        {
            queue.Dequeue() ();
        }
    }
Ejemplo n.º 14
0
        //----------------------------------//

        /// <summary>
        /// Run the next action.
        /// </summary>
        protected void Next()
        {
            while (_queue.Dequeue())
            {
                _queue.Current.Run();
            }
            Interlocked.Exchange(ref _running, 0);
            if (_queue.Count > 0 && Interlocked.CompareExchange(ref _running, 1, 0) == 0)
            {
                _queue.Current.Run();
                Needle.AddSingle(Next);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Allocate an event arg for a receive operation
        /// </summary>
        public static SocketAsyncEventArgs AllocateForReceive(EventHandler <SocketAsyncEventArgs> ioCompletedHandler)
        {
            SocketAsyncEventArgs result;

            if (!_eventArgsReceive.Dequeue(out result))
            {
                result = new SocketAsyncEventArgs();
                result.SetBuffer(BufferCache.Get(), 0, Global.BufferSizeLocal);
            }

            result.Completed += ioCompletedHandler;
            return(result);
        }
Ejemplo n.º 16
0
 virtual protected void UpdateReCalledMsg()
 {
     try {
         if (mToMainThreadMsgList.Count == 0 || mReCallDelgate == null)
         {
             return;
         }
         mReCallDelgate(mToMainThreadMsgList.Dequeue());
     }
     catch (Exception _error)
     {
         DLog.LogError(_error.ToString());
     }
 }
Ejemplo n.º 17
0
        //----------------------------------//

        /// <summary>
        /// Run the next action.
        /// </summary>
        protected void Next()
        {
            if (_queue.Dequeue())
            {
                _queue.Current.Run();
                _needle.AddSingle(Next);
            }
            else
            {
                Interlocked.Decrement(ref _running);
                if (_queue.Count > 0 && Interlocked.CompareExchange(ref _running, 1, 0) == 0)
                {
                    Next();
                }
            }
        }
Ejemplo n.º 18
0
        private void ProcessLogItems(SqliteProfilerDataService dataService)
        {
            LogItem item = null;

            while (!logItems.IsEmpty)
            {
                dataService.BeginTransaction();
                int itemCount = 0;
                while (logItems.Dequeue(out item))
                {
                    dataService.LogCommandExecution(item, this.FullLogging);
                    itemCount++;
                }
                dataService.Commit();
            }
        }
Ejemplo n.º 19
0
    public void SafeQueue_CantTellByDequeueIfQueueIsEmptyOrContainsNull()
    {
        var q = new SafeQueue <string>();

        Assert.IsNotNull(q);
        Assert.AreEqual(true, q.IsEmpty);
        q.Enqueue(null);
        Assert.AreEqual(false, q.IsEmpty);
        var result2 = q.Peek();

        Assert.AreEqual(null, result2);
        Assert.AreEqual(false, q.IsEmpty);
        result2 = q.Dequeue();
        Assert.AreEqual(true, q.IsEmpty);
        Assert.AreEqual(null, result2);
    }
Ejemplo n.º 20
0
        /// <summary>
        /// Releases the current lock or runs the next on available action.
        /// </summary>
        public override void Release()
        {
            var queueStart = _queueStart;

            _queueStart = 1;

            // are there any threads waiting on the lock?
            if (Interlocked.CompareExchange(ref _queueEnd, 1, queueStart) == queueStart)
            {
                // are there any actions waiting on the lock?
                Act act;
                if (_queue.Dequeue(out act))
                {
                    // set the queue start index
                    _queueStart = 1;

                    act.Run();
                }
                else
                {
                    // no, release the lock

                    queueStart  = _queueStart;
                    _queueStart = 0;

                    // flop the locked flag
                    Locked = false;

                    // is the queue empty? yes, set the end
                    if (Interlocked.CompareExchange(ref _queueEnd, 0, queueStart) != queueStart)
                    {
                        // no, re-flip the flag
                        Locked = true;

                        // increment the queue start index
                        _queueStart = queueStart + 1;
                    }
                }
            }
            else
            {
                // yes, increment the queue start index
                _queueStart = queueStart + 1;
            }
        }
Ejemplo n.º 21
0
    public void SafeQueue_passedThroughQueueOperationContains_work()
    {
        var q = new SafeQueue <string>(5);

        Assert.IsNotNull(q);
        Assert.AreEqual(0, q.Count);
        q.Enqueue("a");
        Assert.AreEqual(1, q.Count);
        q.Enqueue("b");
        Assert.AreEqual(2, q.Count);
        q.Enqueue("c");
        Assert.AreEqual(3, q.Count);
        Assert.IsTrue(q.Contains("a"));
        Assert.IsFalse(q.Contains("asdfawe"));
        var outval = q.Dequeue();

        Assert.IsFalse(q.Contains("a"));
    }
Ejemplo n.º 22
0
        /// <summary>
        /// Return a task if there is one.
        /// </summary>
        public override bool Next(out ActionAct task)
        {
            // is the current task still running, has the needle been
            // paused or is the lock already taken?
            if (_paused || !_current.Ready || !_lock.TryTake)
            {
                // yes, return no task
                task = null;
                return(false);
            }

            // get the next task
            while (--_taskCount >= 0 && _tasks.Dequeue())
            {
                if (!_tasks.Current.Remove)
                {
                    _tasks.Enqueue(_tasks.Current);
                }

                // should the task be run?
                if (_tasks.Current.ToRun && _tasks.Current.Ready)
                {
                    // set the current item
                    task           = _current = _tasks.Current;
                    _current.Ready = false;

                    _lock.Release();
                    return(true);
                }
            }

            // get the number of ticks since the last update
            _deltaTicks      = Time.Timestamp - _lastDeltaTicks;
            _lastDeltaTicks += _deltaTicks;

            // no task
            _lock.Release();

            // get the number of tasks to execute next iteration
            _taskCount = _tasks.Count;

            task = null;
            return(false);
        }
Ejemplo n.º 23
0
        private async Task RunTasksInQueue(int maxDegreeOfParallelism = 8)
        {
            var tasksInFlight = new List <Task>(maxDegreeOfParallelism);

            while (_pendingTaskFactories.Any())
            {
                while (tasksInFlight.Count < maxDegreeOfParallelism && _pendingTaskFactories.Any())
                {
                    Func <Task> taskFactory = _pendingTaskFactories.Dequeue();
                    tasksInFlight.Add(taskFactory());
                }

                Task completedTask = await Task.WhenAny(tasksInFlight).ConfigureAwait(false);

                await completedTask.ConfigureAwait(false);

                tasksInFlight.Remove(completedTask);
            }
        }
Ejemplo n.º 24
0
        public async Task RunTasksInQueue(int maxDegreeOfParallelism = 8)
        {
            var tasksInFlight = new List <Task>(maxDegreeOfParallelism);

            while (_pendingTaskFactories.Any() || tasksInFlight.Any())
            {
                while (tasksInFlight.Count < maxDegreeOfParallelism && _pendingTaskFactories.Any())
                {
                    Func <Task> taskFactory = _pendingTaskFactories.Dequeue();
                    tasksInFlight.Add(taskFactory());
                    this._logger.LogDebug($"Engine selected one job to run. Currently there are still {_pendingTaskFactories.Count()} jobs remaining. {tasksInFlight.Count} jobs running.");
                }

                Task completedTask = await Task.WhenAny(tasksInFlight).ConfigureAwait(false);

                await completedTask.ConfigureAwait(false);

                this._logger.LogInformation($"Engine finished one job. Currently there are still {_pendingTaskFactories.Count()} jobs remaining. {tasksInFlight.Count} jobs running.");
                tasksInFlight.Remove(completedTask);
            }
        }
Ejemplo n.º 25
0
            virtual public void UpdateRecMsg()
            {
                if (StopUpdateRecMsg)
                {
                    return;
                }

                int i = mResultDataList.Count > OneFixedUpdateChoseCount ? OneFixedUpdateChoseCount: mResultDataList.Count;

                while (i > 0)
                {
                    try
                    {
                        ReceiveData trecdata = mResultDataList.Dequeue();
                        Call(trecdata.Cmd, trecdata);
                        i--;
                    }
                    catch (Exception _error)
                    {
                        DLog.LogError(_error.ToString());
                    }
                }
            }
Ejemplo n.º 26
0
        private void startSend()
        {
            Exception e = null;

            while (clientRun)
            {
                var msg = sendQueue.Dequeue();
                if (msg == null)
                {
                    sendEvent.WaitOne();
                    continue;
                }
                e = netProtocol.Send(msg);
                if (e != null)
                {
                    OnError(e.ToString());
                    if (clientRun)
                    {
                        throw e;
                    }
                }
            }
        }
Ejemplo n.º 27
0
 // 接受服务端发送的消息 调用相关的回调函数
 public void MyUpdate()
 {
     while (reciveQueue.Count > 0)
     {
         var  msg = reciveQueue.Dequeue();
         uint session;
         var  recData = DataPack.UnPack(msg, out session);
         if (recData.Length <= 0)
         {
             // 心跳包,重置心跳计数
             heartCount = 0;
             continue;
         }
         if (session == 0)
         {
             RpcNotify(recData);
         }
         else if (sessionToCallback.ContainsKey(session))
         {
             var callback = sessionToCallback[session].CallBackFunc;
             if (null != callback)
             {
                 callback(recData);
             }
             // 加锁删除数据
             lock (sessionToCallback)
             {
                 sessionToCallback.Remove(session);
                 netProtocol.WaitRecive--;
             }
         }
         else
         {
             DebugLogger.DebugError("Session invalid:" + session);
         }
     }
 }
Ejemplo n.º 28
0
    // Update is called once per frame
    void Update()
    {
        if ((gbEventQueue != null) && (!gbEventQueue.isEmpty()))
        {
            GameBoardEvent cur = gbEventQueue.Dequeue();
            this.doGameEvent(cur);
        }

        for (int row = 0; row < board.Count; row++)
        {
            for (int col = 0; col < board[row].Count; col++)
            {
                bool muddy = board[row][col].type == TileType.Dirty;

                boardObj[row][col].GetComponent <Renderer>().enabled = muddy;
            }
        }

        //TESTING THE LEVEL LOADING
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            loadLevel(1);
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            loadLevel(2);
        }
        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            loadLevel(3);
        }
        if (Input.GetKeyDown(KeyCode.Alpha4))
        {
            loadLevel(4);
        }
    }
Ejemplo n.º 29
0
        /// <summary>
        /// Ütemesen nézzük mi a helyzet az adapterrel
        /// </summary>
        private void DoWork()
        {
            _isRunning = true;
            Exception loopException = null;

            {
                /*SynContext*/
                Action doMehtod = () => OnStarted();
                if (App.SyncContext != null)
                {
                    App.SyncContext.Post((e1) => { doMehtod(); }, null);
                }
                else
                {
                    doMehtod();
                }
            }

            do
            {
                if (_adapter != null && _adapter.IsConnected)
                {
                    if (_adapter.LasException != null)
                    {
                        Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): DoWork is now shutdown by Adapter LastException is not null.");
                        loopException = _adapter.LasException;
                        break;
                    }

                    /*
                     * TODO: Ezt megcsinálni a ToolTable-re is
                     * if (_messageSenders.LastException != null)
                     * {
                     *  Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): DoWork is now shutdown by MessageSender LastException is not null.");
                     *  loopException = _messageSenders.LastException;
                     *  break;
                     * }
                     */
                    try
                    {
                        #region CAN Adapter Funcitons

                        if (_txQueue.Count > 0)
                        {
                            var tx          = _txQueue.Dequeue();
                            var txTimestamp = DateTime.Now;
                            var txTrace     = new MessageTraceItem(
                                name:           tx.Name,
                                timestamp:      txTimestamp,
                                direction:      MessageDirection.Transmitted,
                                type:           tx.Type,
                                remote:         tx.Remote,
                                arbitrationId:  tx.ArbitrationId,
                                data:           tx.Data,
                                documentation:  tx.Documentation,
                                description:    tx.Description);

                            _adapter.Write(new[]
                            {
                                new CanMessage(
                                    isRemote:       tx.Remote ? (byte)0x01 : (byte)0x00b,
                                    arbitrationId:  (tx.Type == ArbitrationIdType.Standard) ? tx.ArbitrationId : tx.ArbitrationId | 0x20000000,
                                    data:           tx.Data)
                            });
                            if (!_paramters.FiltersEnabled || _filters.DoAddToTrace(
                                    arbitrationId: tx.ArbitrationId,
                                    type:          tx.Type,
                                    remote:        tx.Remote,
                                    direction:     MessageDirection.Transmitted))
                            {
                                if (_project.Parameters.TraceEnabled)
                                {
                                    _messageTrace.Add(txTrace);
                                }
                            }

                            if (!_paramters.FiltersEnabled || _filters.DoAddToLog(
                                    arbitrationId: tx.ArbitrationId,
                                    type:          tx.Type,
                                    remote:        tx.Remote,
                                    direction:     MessageDirection.Transmitted))
                            {
                                if (_project.Parameters.LogEnabled)
                                {
                                    _log.Messages.AddToStorage(
                                        name:          tx.Name,
                                        timestamp:     txTimestamp,
                                        direction:     MessageDirection.Transmitted,
                                        type:          tx.Type,
                                        arbitrationId: tx.ArbitrationId,
                                        isRemote:      tx.Remote,
                                        data:          tx.Data,
                                        documentation: tx.Documentation,
                                        description:   tx.Description);
                                }
                            }

                            if (_project.Parameters.MessageStatisticsEnabled)
                            {
                                Action doMehtod = () =>/*SynContext*/
                                {
                                    _messageStat.InsertMessage(
                                        name:          tx.Name,
                                        direction:     MessageDirection.Transmitted,
                                        type:          tx.Type,
                                        arbitrationId: tx.ArbitrationId,
                                        data:          tx.Data,
                                        remote:        tx.Remote,
                                        timestamp:     txTimestamp);
                                };
                                if (App.SyncContext != null)
                                {
                                    App.SyncContext.Post((e1) => { doMehtod(); }, null);
                                }
                                else
                                {
                                    doMehtod();
                                }
                            }
                        }

                        if (_adapter.Attributes.PendingRxMessages > 0)
                        {
                            var rxItems = new CanMessage[1];
                            _adapter.Read(rxItems, 0, 1);

                            var rxType          = ((rxItems[0].ArbitrationId & 0x20000000) == 0) ? ArbitrationIdType.Standard : ArbitrationIdType.Extended;
                            var rxArbId         = unchecked (rxItems[0].ArbitrationId & (uint)(~0x20000000));
                            var rxIsRmote       = rxItems[0].IsRemote != 0 ? true : false;
                            var rxTimestamp     = new DateTime(rxItems[0].TimestampTick);
                            var rxData          = rxItems[0].Data;
                            var rxName          = string.Empty;
                            var rxDocumentation = string.Empty;
                            var rxDescription   = string.Empty;

                            /*
                             * TODO: Ezt megcsinálni
                             * if (_paramters.RxMsgResolvingBySenderEnabled)
                             * {
                             *  var resolvedRxMsg = _messageSenders.GetMsg(rxArbId, rxType, rxIsRmote);
                             *  if (resolvedRxMsg != null)
                             *  {
                             *      rxName = resolvedRxMsg.Name;
                             *      rxDocumentation = resolvedRxMsg.Documentation;
                             *      rxDescription = resolvedRxMsg.Description;
                             *  }
                             * }
                             */

                            var rxTrace = new MessageTraceItem(
                                name:          rxName,
                                timestamp:     rxTimestamp,
                                direction:     MessageDirection.Received,
                                type:          rxType,
                                remote:        rxIsRmote,
                                arbitrationId: rxArbId,
                                data:          rxData,
                                documentation: rxDocumentation,
                                description:   rxDescription);

                            if (!_paramters.FiltersEnabled || _filters.DoAddToTrace(
                                    arbitrationId: rxArbId,
                                    type:          rxType,
                                    remote:        rxIsRmote,
                                    direction:     MessageDirection.Received))
                            {
                                if (_paramters.TraceEnabled)
                                {
                                    _messageTrace.Add(rxTrace);
                                }
                            }

                            if (!_paramters.FiltersEnabled || _filters.DoAddToLog(
                                    arbitrationId: rxArbId,
                                    type:          rxType,
                                    remote:        rxIsRmote,
                                    direction:     MessageDirection.Received))
                            {
                                if (_paramters.LogEnabled)
                                {
                                    _log.Messages.AddToStorage(
                                        name:           rxName,
                                        timestamp:      rxTimestamp,
                                        direction:      MessageDirection.Received,
                                        type:           rxType,
                                        arbitrationId:  rxArbId,
                                        isRemote:       rxIsRmote,
                                        data:           rxData,
                                        documentation:  rxDocumentation,
                                        description:    rxDescription);
                                }
                            }
                            if (_paramters.MessageStatisticsEnabled)
                            {
                                Action doMehtod = () =>/*SynContext*/
                                {
                                    _messageStat.InsertMessage(
                                        name:          rxName,
                                        direction:     MessageDirection.Received,
                                        type:          rxType,
                                        arbitrationId: rxArbId,
                                        data:          rxData,
                                        remote:        rxIsRmote,
                                        timestamp:     rxTimestamp);
                                };
                                if (App.SyncContext != null)
                                {
                                    App.SyncContext.Post((e1) => { doMehtod(); }, null);
                                }
                                else
                                {
                                    doMehtod();
                                }
                            }
                        }

                        if (_paramters.AdapterStatisticsEnabled)
                        {
                            /*Statiszitikai az adapter követi. Az értkékeket időnként le kell kérdezni tőle.*/
                            /*Az adapter leállítását követően még egyszer LE KELL KÉRDEZNI, hogy az UI-n az UTOLSÓ érték látszódjon.*/
                            long nowDateTimeTicks = DateTime.Now.Ticks;
                            if ((nowDateTimeTicks - _statusUpdateTimestamp) > 10000 * 1000)
                            {
                                AppDiagService.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): Adapter Staistics Poll Now... DiffTime: " + ((DateTime.Now.Ticks - _statusUpdateTimestamp) / 10000).ToString("N4") + "ms");

                                _statusUpdateTimestamp = nowDateTimeTicks;
                                _adapterStat.UpdateReceived(
                                    total:   _adapter.Attributes.RxTotal,
                                    drop:    _adapter.Attributes.RxDrop,
                                    error:   _adapter.Attributes.RxErrorCounter,
                                    pending: _adapter.Attributes.PendingRxMessages);
                                _adapterStat.UpdateTransmitted(
                                    total:   _adapter.Attributes.TxTotal,
                                    drop:    _adapter.Attributes.TxDrop,
                                    error:   _adapter.Attributes.TxErrorCounter,
                                    pending: _txQueue.Count);
                            }
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): DoWork is now shutdown by Loop Fuction Exception.");
                        loopException = ex;
                        break;
                    }
                }
                else
                {
                    try
                    {
                        #region Virtual CAN Adapter Funcitions

                        /*Virtuaális adapter*/
                        if (_txQueue.Count > 0)
                        {
                            _virtualAdapterFrameCounter++;

                            var tx      = _txQueue.Dequeue();
                            var txTrace = new MessageTraceItem(
                                name:          tx.Name,
                                timestamp:     DateTime.Now,
                                direction:     MessageDirection.Transmitted,
                                type:          tx.Type,
                                remote:        tx.Remote,
                                arbitrationId: tx.ArbitrationId,
                                data:          tx.Data,
                                documentation: tx.Documentation,
                                description:   tx.Description);
                            if (!_paramters.FiltersEnabled || _filters.DoAddToTrace(
                                    arbitrationId: tx.ArbitrationId,
                                    type:          tx.Type,
                                    remote:        tx.Remote,
                                    direction:     MessageDirection.Transmitted))
                            {
                                if (_paramters.TraceEnabled)
                                {
                                    _messageTrace.Add(txTrace);
                                }
                            }

                            if (!_paramters.FiltersEnabled || _filters.DoAddToLog(
                                    arbitrationId: tx.ArbitrationId,
                                    type:          tx.Type,
                                    remote:        tx.Remote,
                                    direction:     MessageDirection.Transmitted))
                            {
                                if (_project.Parameters.LogEnabled)
                                {
                                    _log.Messages.AddToStorage(
                                        name:          tx.Name,
                                        timestamp:     DateTime.Now,
                                        direction:     MessageDirection.Transmitted,
                                        type:          tx.Type,
                                        arbitrationId: tx.ArbitrationId,
                                        isRemote:      tx.Remote,
                                        data:          tx.Data,
                                        documentation: tx.Documentation,
                                        description:   tx.Description);
                                }
                            }

                            if (_paramters.MessageStatisticsEnabled)
                            {
                                Action doMehtod = () =>
                                {
                                    _messageStat.InsertMessage(
                                        name:          tx.Name,
                                        direction:    MessageDirection.Transmitted,
                                        type:          tx.Type,
                                        arbitrationId: tx.ArbitrationId,
                                        data:          tx.Data,
                                        remote:        tx.Remote,
                                        timestamp:     DateTime.Now);
                                };
                                if (App.SyncContext != null)
                                {
                                    App.SyncContext.Post((e1) => { doMehtod(); }, null);
                                }
                                else
                                {
                                    doMehtod();
                                }
                            }
                        }
                        if (_paramters.AdapterStatisticsEnabled)
                        {
                            /*Statiszitikai az adapter követi. Az értkékeket időnként le kell kérdezni tőle.*/
                            /*Az adapter leállítását követően még egyszer LE KELL KÉRDEZNI, hogy az UI-n az UTOLSÓ érték látszódjon.*/
                            long nowDateTimeTicks = DateTime.Now.Ticks;
                            if ((nowDateTimeTicks - _statusUpdateTimestamp) > 10000 * 1000)
                            {
                                AppDiagService.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): Virtual Adapter Staistics Poll Now... DiffTime: " + ((DateTime.Now.Ticks - _statusUpdateTimestamp) / 10000).ToString("N4") + "ms");
                                _statusUpdateTimestamp = nowDateTimeTicks;
                                _adapterStat.UpdateTransmitted(
                                    total:   _virtualAdapterFrameCounter,
                                    drop:    0,
                                    error:   0,
                                    pending: _txQueue.Count);
                            }
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): DoWork is now shutdown by Loop Fuction Exception.");
                        loopException = ex;
                        break;
                    }
                }
                if (_shutdownEvent.WaitOne(0))
                {
                    Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): DoWork is now shutdown!");
                    break;
                }
            } while (_isRunning);
            /*Probléma megjelnítése*/
            if (loopException != null)
            {
                new ErrorHandlerService().Show(loopException);
            }

            #region Update Last State

            if (loopException == null)
            { /*Csak ha nem volt gebasz az adapterrel...*/
                if (_paramters.DeviceName != VirtualDeviceName && _adapter.IsConnected)
                {
                    /*Statisztika lefrissítése az UI-nak*/
                    _adapterStat.UpdateReceived(
                        total:   _adapter.Attributes.RxTotal,
                        drop:    _adapter.Attributes.RxDrop,
                        error:   _adapter.Attributes.RxErrorCounter,
                        pending: _adapter.Attributes.PendingRxMessages);
                    _adapterStat.UpdateTransmitted(
                        total:   _adapter.Attributes.TxTotal,
                        drop:    _adapter.Attributes.TxDrop,
                        error:   _adapter.Attributes.TxErrorCounter,
                        pending: _txQueue.Count);
                    _adapter.Disconnect();
                }
                else
                {
                    _adapterStat.UpdateTransmitted(
                        total:   _virtualAdapterFrameCounter,
                        drop:    0,
                        error:   0,
                        pending: _txQueue.Count);
                }
            }
            #endregion

            #region Resource Freeing
            if (_adapter != null)
            {
                _adapter.Dispose();
                _adapter = null;
            }

            // _messageSenders.Stop();
            _readyToDisposeEvent.Set();
            _isRunning = false;
            _toolTables.Stop();
            #endregion

            #region Loop Terminate
            {
                /*SynContext*/
                Action doMehtod = () =>
                {
                    try
                    {
                        if (_project.Parameters.LogEnabled)
                        {
                            _log.Messages.AddToStorageEnd();
                            _logFiles.Add(_log);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        /*Minden áron jelezni kell! hogy megállt.*/
                        OnStopped();
                        Debug.WriteLine(GetType().Namespace + "." + GetType().Name + "." + MethodBase.GetCurrentMethod().Name + "(): Loop is colsed...");
                    }
                };
                if (App.SyncContext != null)
                {
                    App.SyncContext.Post((e1) => { doMehtod(); }, null);
                }
                else
                {
                    doMehtod();
                }
            }
            #endregion
        }
Ejemplo n.º 30
0
    private static void ThreadProc(object state)
    {
        DateTime finish = DateTime.Now.AddSeconds(10);
        Random   rand   = new Random();

        int[] result    = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int   threadNum = (int)state;

        while (DateTime.Now < finish)

        {
            int what = rand.Next(250);
            int how  = rand.Next(100);

            if (how < 16)
            {
                q.Enqueue(what);
                result[(int)ThreadResultIndex.EnqueueCt] += 1;
            }
            else if (how < 32)
            {
                if (q.TryEnqueue(what))
                {
                    result[(int)ThreadResultIndex.TryEnqueueSucceedCt] += 1;
                }
                else
                {
                    result[(int)ThreadResultIndex.TryEnqueueFailCt] += 1;
                }
            }
            else if (how < 48)
            {
                // Even a very small wait significantly increases the success
                // rate of the conditional enqueue operation.
                if (q.TryEnqueue(what, 10))
                {
                    result[(int)ThreadResultIndex.TryEnqueueWaitSucceedCt] += 1;
                }
                else
                {
                    result[(int)ThreadResultIndex.TryEnqueueWaitFailCt] += 1;
                }
            }
            else if (how < 96)
            {
                result[(int)ThreadResultIndex.DequeueCt] += 1;
                try
                {
                    q.Dequeue();
                }
                catch
                {
                    result[(int)ThreadResultIndex.DequeueExCt] += 1;
                }
            }
            else
            {
                result[(int)ThreadResultIndex.RemoveCt]  += 1;
                result[(int)ThreadResultIndex.RemovedCt] += q.Remove(what);
            }
        }

        results[threadNum] = result;

        if (0 == Interlocked.Decrement(ref threadsRunning))
        {
            StringBuilder sb = new StringBuilder(
                "                               Thread 1 Thread 2 Thread 3    Total\n");

            for (int row = 0; row < 9; row++)
            {
                int total = 0;
                sb.Append(titles[row]);

                for (int col = 0; col < 3; col++)
                {
                    sb.Append(String.Format("{0,9}", results[col][row]));
                    total += results[col][row];
                }

                sb.AppendLine(String.Format("{0,9}", total));
            }

            Console.WriteLine(sb.ToString());
        }
    }
Ejemplo n.º 31
0
        static void TestQueue()
        {
            Thread[] threads = new Thread[8];
            var queue = new SafeQueue<int>();
            var signal = new AutoResetEvent(false);

            HashSet<int> integers = new HashSet<int>();

            isRunning = true;

            Thread queueReader = new Thread(new ThreadStart(delegate
            {
                while (true)
                {
                    signal.WaitOne();
                    int n;
                    int count = 0;
                    while (queue.Dequeue(out n))
                    {
                        integers.Add(n);
                        count++;
                    }
                    //Console.WriteLine(count);
                    if (!isRunning) return;
                }
            }));

            queueReader.Start();

            Action<int> enqueue = (s) =>
            {
                for (int x = 0; x < 100000; x++)
                {
                    queue.Enqueue(s + x);
                    signal.Set();
                    if (x % 100 == 0) Thread.Yield();
                }
            };

            int start = 0;
            for (int i = 0; i < 8; i++)
            {

                threads[i] = new Thread(new ParameterizedThreadStart((state) => enqueue((int)state)));
                threads[i].Start(start);
                start += 100000;
            }

            for (int i = 0; i < 8; i++)
            {
                threads[i].Join();
            }
            Thread.Yield();
            isRunning = false;
            signal.Set();

            queueReader.Join();

            bool failed = false;
            for (int i = 0; i < 800000; i++)
            {
                if (!integers.Contains(i))
                {
                    //Console.WriteLine("{0} failed", i);
                    failed = true;
                }
            }
            if (failed) Console.WriteLine("Test failed");
        }