Beispiel #1
0
        /// <summary>
        ///     Clears the work item queue.
        /// </summary>
        public void ClearWorkItemQueue()
        {
            var wi = workItemQueue.Dequeue();

            while (wi != null)
            {
                wi = workItemQueue.Dequeue();
            }
        }
Beispiel #2
0
        // Update is called once per frame
        void Update()
        {
            bool transmitLocal  = localCollectors.Any(c => c.Collecting);
            bool transmitRemote = Mode == LogManagerMode.Transmit;
            bool holdLogs       = Mode == LogManagerMode.Hold;

            if (transmitLocal || transmitRemote)
            {
                JsonWriter writer;
                while (events.Dequeue(out writer))
                {
                    try
                    {
                        if (transmitRemote)
                        {
                            var message = LogManagerMessage.Rent(writer.GetSpan(), writer.Tag);
                            message.objectid    = LogCollector.Id;
                            message.componentid = LogCollector.ComponentId;
                            context.Send(message);
                        }

                        if (transmitLocal)
                        {
                            foreach (var item in localCollectors)
                            {
                                item.Push(writer.GetSpan(), writer.Tag);
                            }
                        }
                    }
                    finally
                    {
                        Release(ref writer);
                    }
                }
            }

            if (!holdLogs)
            {
                while (Memory > MaxMemory) // If the queued events are taking up too much space, then dump them starting from the back of the queue
                {
                    JsonWriter writer;
                    if (events.Dequeue(out writer))
                    {
                        Release(ref writer);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Beispiel #3
0
        void Update()
        {
            var output = new ArucoOutput();

            while (_currentOutput.Dequeue(out output))
            {
                // TODO: processor only processes markers on left image at the moment!
                foreach (var marker in output.markers_left)
                {
                    var markerPose = ProcessOutput(marker);
                    OnNewPoseDetected(markerPose);
                }
            }

            // TODO: refactor
            bool hasPropertyChanged =
                (_prevUseTracker != UseTracker) ||
                (_prevTrackerErrorRatio != TrackerErrorRatio);

            if (hasPropertyChanged)
            {
                _arProcessor.UseTracker        = UseTracker;
                _arProcessor.TrackerErrorRatio = TrackerErrorRatio;
                UpdateProcessorProperties();
            }
        }
        private void OnSynchronize(object sender, ElapsedTimerEventArgs e)
        {
            var changesMade = false;

            if (1 == (int)_opverlappingChecker)
            {
                return;
            }
            _opverlappingChecker = 1;
            try
            {
                var maxMessages = (int)MaxMessagesPerCycle;
                foreach (var request in _requestsQueue.Dequeue(100))
                {
                    if (HandledEvent(request))
                    {
                        changesMade = true;
                    }
                    maxMessages--;
                    if (maxMessages <= 0)
                    {
                        break;
                    }
                }
                if (changesMade)
                {
                    _list.Data = new List <T>(_trustedSource);
                }
            }
            finally
            {
                _opverlappingChecker = 0;
            }
        }
    // Update is called once per frame
    void Update()
    {
        string clientId;

        if (PlayerSpawnQueue.Dequeue(out clientId))
        {
            if (!ClientContext.ClientContexts.ContainsKey(clientId))
            {
                /* This connection doesnt have a context... new player! */

                var entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(playerPrefab, World.Active);
                var entity       = em.Instantiate(entityPrefab);

                /* Network component stores the connection index on the entity. */
                //  var networkComponent = new NetworkComponent() {clientId = clientId};
                //em.AddComponentData(entity, networkComponent);

                Translation translation = em.GetComponentData <Translation>(entity);
                translation.Value = new float3(0.0f, -0.5f, 0.0f);

                ClientContext ctx = new ClientContext();
                ctx.clientId     = clientId;
                ctx.playerEntity = entity;

                ClientContext.ClientContexts.Add(clientId, ctx);

                NetworkState.playerEntityCache.Add(clientId, entity);
            }
        }
    }
Beispiel #6
0
    // Update is called once per frame
    void Update()
    {
        MoveMessage movemsg;

        if (queue.Dequeue(out movemsg))
        {
            Debug.Log("RJ MOVE:" + movemsg.movePost);
            Entity            player = NetworkState.playerEntityCache[movemsg.clientId];
            MovementComponent move   = World.Active.EntityManager.GetComponentData <MovementComponent>(player);
            move.playerDirectionAxis = movemsg.movePost;
            World.Active.EntityManager.SetComponentData(player, move);

            /*
             * EntityQuery query = World.Active.EntityManager.CreateEntityQuery(typeof(Player1_tag));
             * using (var players = query.ToEntityArray(Allocator.Persistent))
             * {
             *  Debug.Log("RJ found players:"+players.Length);
             *  foreach (var p in players)
             *  {
             *      Debug.Log("Player:"+p.Index);
             *      MovementComponent move = World.Active.EntityManager.GetComponentData<MovementComponent>(p);
             *      move.playerDirectionAxis = movemsg.movePost;
             *      World.Active.EntityManager.SetComponentData(p, move);
             *  }
             * }
             */
        }
    }
Beispiel #7
0
        private WorkItem GetWorkItem(CallbackFunction asyncCallback)
        {
            var workItem = returnedWorkItems.Dequeue();

            if (workItem == null)
            {
                workItem = new WorkItem();
                workItem.WorkItemStateTypeless = new WorkItemStateTypeless(workItem);
            }

            workItem.SingleThreadRunner = null;
            workItem.IsCompleted        = false;
            workItem.Result             = null;
            workItem.AsyncCallback      = asyncCallback;
            return(workItem);
        }
 public void Update()
 {
     while (!refGCList.IsEmpty())
     {
         int reference = refGCList.Dequeue();
         LuaDLL.lua_unref(lua.L, reference);
     }
 }
Beispiel #9
0
        private void timerMessages_Tick(object sender, EventArgs e)
        {
            string message = "";

            if (messageQueue.Dequeue(out message))
            {
                rtbConsole.AppendText(message);
                ScrollToCarret(rtbConsole);
            }
        }
Beispiel #10
0
        /// <summary>
        ///Dequeue 的测试
        ///</summary>
        public void DequeueTestHelper <ValueT>()
        {
            LockFreeQueue <ValueT> target = new LockFreeQueue <ValueT>(); // TODO: 初始化为适当的值
            ValueT expected = default(ValueT);                            // TODO: 初始化为适当的值
            ValueT actual;

            actual = target.Dequeue();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Beispiel #11
0
 void FixedUpdate()
 {
     if (OnMessageReceived != null)
     {
         IncomingCommand cmd = new IncomingCommand();
         while (_queuedCommands.Dequeue(out cmd))
         {
             OnMessageReceived(cmd);
         }
     }
 }
Beispiel #12
0
    void TickUnref()
    {
        if (Time.frameCount % 30 != 0)
        {
            return;
        }

        while (!_refGCList.IsEmpty())
        {
            LuaRef lf = _refGCList.Dequeue();
            LuaDLL.lua_unref(lf.L, lf.reference);
        }
    }
Beispiel #13
0
        public static void ConsumerThread()
        {
            while (_toSendElements != Interlocked.Read(ref _collectedElements))
            {
#pragma warning disable 168
                // ReSharper disable once UnusedVariable
                foreach (CollectionElement ce in _internalQueue.Dequeue())
#pragma warning restore 168
                {
                    Interlocked.Increment(ref _collectedElements);
                }
            }
        }
Beispiel #14
0
    void Update()
    {
        //lock (queueOfInputs) {
        //while (queueOfInputs.Count > 0) {
        bool next = false;

        do
        {
            //string line = queueOfInputs.Dequeue();
            string line;
            next = queue.Dequeue(out line);
            if (next)
            {
                StartCoroutine(UseData(line));
            }
        }while(next);
        //}
    }
Beispiel #15
0
        public void LockFreeQueueDequeueMultiple()
        {
            var queue = new LockFreeQueue <int>();

            //We enqueue some items to test
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);

            var result = queue.Dequeue(3).ToArray();

            Assert.AreEqual(3, result.Count());
            Assert.AreEqual(1, result[0]);
            Assert.AreEqual(2, result[1]);
            Assert.AreEqual(3, result[2]);
        }
Beispiel #16
0
 public override IEnumerable <Step> Run()
 {
     while (Thread.Status != CoroutineThreadStatus.Running)
     {
         foreach (var newEvt in _eventDescriptorsQueue.Dequeue(100))
         {
             if (!_eventsDescriptors.ContainsKey(newEvt.EventName))
             {
                 _eventsDescriptors.Add(newEvt.EventName, new Dictionary <Type, CoroutineEventDescriptor>());
             }
             if (!_eventsDescriptors[newEvt.EventName].ContainsKey(newEvt.EventArgType))
             {
                 _eventsDescriptors[newEvt.EventName].Add(newEvt.EventArgType, newEvt);
             }
         }
         yield return(Step.Current);
     }
 }
Beispiel #17
0
        /// <summary>
        ///     Enqueues the work item.
        /// </summary>
        /// <param name="workItem">The work item.</param>
        internal void EnqueueWorkItemInternal(WorkItem workItem)
        {
            // look for an idle worker...
            var singleThreadRunner = threadsIdle.Dequeue();

            Thread.MemoryBarrier();
            if (singleThreadRunner != null)
            {
                // hand over the work item...
                workItem.SingleThreadRunner = singleThreadRunner;
                Interlocked.Increment(ref threadsWorking);
                singleThreadRunner.SignalWork(workItem);
            }
            else
            {
                // just enqueue the item since all workers are busy...
                workItemQueue.Enqueue(workItem);
            }
        }
Beispiel #18
0
        void Update()
        {
            var output = new ArucoOutput();

            while (_currentOutput.Dequeue(out output))
            {
                // TODO: processor only processes markers on left image at the moment!
                foreach (var marker in output.markers_left)
                {
                    var markerPose = ProcessOutput(marker);

                    if (DetectedPoses.ContainsKey(marker.id))
                    {
                        DetectedPoses[marker.id] = markerPose;
                    }
                    else
                    {
                        DetectedPoses.Add(marker.id, markerPose);
                    }

                    if (NewPoseDetected != null)
                    {
                        NewPoseDetected(markerPose);
                    }
                }
            }

            // TODO: refactor
            bool hasPropertyChanged =
                (_prevMarkerSize != MarkerSizeInMeter) ||
                (_prevTrackerErrorRatio != TrackerErrorRatio);

            if (hasPropertyChanged)
            {
                _arProcessor.MarkerSizeInMeter = MarkerSizeInMeter;
                _arProcessor.TrackerErrorRatio = TrackerErrorRatio;

                _arProcessor.UpdateProperties();

                _prevMarkerSize        = MarkerSizeInMeter;
                _prevTrackerErrorRatio = TrackerErrorRatio;
            }
        }
Beispiel #19
0
 public override IEnumerable <Step> Run()
 {
     while (Thread.Status != CoroutineThreadStatus.Running)
     {
         foreach (Coroutines.EventMessage newEvt in _events.Dequeue(100))
         {
             if (_eventsList.ContainsKey(newEvt.EventName) && newEvt.Data != null)
             {
                 var type = newEvt.Data.GetType();
                 if (_eventsList[newEvt.EventName].ContainsKey(type))
                 {
                     var handler = _eventsList[newEvt.EventName][type];
                     var where = _counter.Value % _threads.Length;
                     _threads[where].AddCoroutine(new ExecEventCoroutine(handler, newEvt));
                 }
             }
         }
         yield return(Step.Current);
     }
 }
Beispiel #20
0
        void ExecuteThread()
        {
            s_ThreadWaitTime = 1;
            while (!m_ShouldStopThreads && m_ActionQueue != null)
            {
                // Wait
                if (!m_QueueIsNotEmptyEvent.WaitOne(s_ThreadWaitTime) && m_ActionQueue.isEmpty)
                {
                    if (s_ThreadWaitTime < 8)
                    {
                        s_ThreadWaitTime *= 2;
                    }
                    continue;
                }

                // Try to dequeue
                var action = m_ActionQueue.Dequeue();

                // We missed, queue is empty
                if (action == null)
                {
                    m_QueueIsNotEmptyEvent.Reset();
                    continue;
                }

                s_ThreadWaitTime = 1;

                try
                {
                    action();
                }
                catch (Exception e)
                {
                    if (!(e is ThreadAbortException))
                    {
                        FluvioDebug.LogError(string.Format("Unhandled {0} caught on background thread ({1}) - task aborted.\n{2}", e.GetType().Name, e.Message, e.StackTrace), this);
                    }
                }
            }
        }
Beispiel #21
0
 public void WorkerThread()
 {
     while (isRunning)
     {
         if (statements.Count > 0)
         {
             DatabaseAction action = null;
             if (statements.Dequeue(out action))
             {
                 action.Action.Invoke();
             }
             else
             {
                 Thread.Sleep(10);
             }
         }
         else
         {
             Thread.Sleep(10);
         }
     }
 }
Beispiel #22
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TEventArgs"></typeparam>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSlice(object sender, BaseWorldEventArgs eventArgs)
        {
            //////////////////////////////////////////////////////////////////////////
            // WOW世界的全部物体开始更新

            // 现在的时间
            DateTime nowTime = DateTime.Now;

            // 用于计算经过的时间(因为Stopwatch的计算速度比DateTime.Now快近3倍)
            Stopwatch updateTime = Stopwatch.StartNew();

            ISupportSlice[] updateSliceArray = m_NeedUpdateQueue.Dequeue();
            if (updateSliceArray != null)
            {
                for (int iIndex = 0; iIndex < updateSliceArray.Length; iIndex++)
                {
                    var updateSlice = updateSliceArray[iIndex];

                    // 进入锁定
                    if (updateSlice.InLockProcessSlice() == false)
                    {
                        continue;
                    }

                    // 只允许单线程内处理调用
                    updateSlice.OnProcessSlice(nowTime + updateTime.Elapsed);

                    // 离开锁定
                    updateSlice.OutLockProcessSlice();
                }

                // 先处理部分,然后再次处理剩下的
                base.SetWorldSignal();
            }

            // 计算结束
            updateTime.Stop();
        }
Beispiel #23
0
        private void Worker(object obj)
        {
            Tuple <String, String> item;

            while (IsRunning)
            {
                while (_queue.Dequeue(out item))
                {
                    if (item != null && !String.IsNullOrEmpty(item.Item1) && !String.IsNullOrEmpty(item.Item2))
                    {
                        try
                        {
                            String filePath = Path.Combine(_cachePath, item.Item2);
                            if (!File.Exists(filePath))
                            {
                                using (var w = new WebClient())
                                {
                                    w.Proxy = null;
                                    w.DownloadFile(item.Item1, filePath);
                                    Thread.Sleep(1);
                                }
                            }
                        }
                        catch
                        {
                            _queue.Enqueue(item);
                        }
                    }
                    if (CacheStored != null)
                    {
                        CacheStored(this, new CacheStoredEventArgs(item.Item2));
                    }
                    Thread.Sleep(1);
                }
                Thread.Sleep(50);
            }
        }
Beispiel #24
0
    void Update()
    {
        bool doTryConnect = true;

        doTryConnect = doTryConnect && !connected && UriString != "";
        if (cws != null)
        {
            doTryConnect = doTryConnect && (cws.State == WebSocketState.Closed || cws.State == WebSocketState.Aborted);
        }

        if (doTryConnect)
        {
            connected = true;
            cws       = null;
            TryConnect();
        }

        CKARNetworkState state;

        while (stateQueue.Dequeue(out state))
        {
            EventManager.InvokeNetworkStateChange(state);
        }

        string msgString;

        while (queue.Dequeue(out msgString))
        {
            Debug.Log(msgString);
            if (msgString.Contains("\"type\": \"transform\""))
            {
                WebsocketJsonTransform msg = JsonUtility.FromJson <WebsocketJsonTransform>(msgString);
                TransformSpec          ts  = new TransformSpec(msg.position, msg.scale, msg.rotation);
                if (msg.tree.Contains("marker"))
                {
                    EventManager.InvokeMarkerTransform(msg.tree, ts);
                }
                else if (msg.tree.Contains("master"))
                {
                    EventManager.InvokeMasterTransform(ts);
                }
                else
                {
                    lsysController.DispatchTransform(msg.tree, ts);
                }
            }
            else if (msgString.Contains("\"type\": \"shape\""))
            {
                WebsocketJsonShape msg = JsonUtility.FromJson <WebsocketJsonShape>(msgString);
                lsysController.DispatchShape(msg.tree, msg.shape);
            }
            else if (msgString.Contains("\"type\": \"value\""))
            {
                WebsocketJsonValue msg  = JsonUtility.FromJson <WebsocketJsonValue>(msgString);
                string[]           keys = msg.key.Split(',');
                foreach (string key in keys)
                {
                    ValueStore.Set(key, msg.payload); // will also invoke event
                }
            }
            else
            {
                WebsocketJsonMessage msg = JsonUtility.FromJson <WebsocketJsonMessage>(msgString);
                if (msg.type == "lsys")
                {
                    lsysController.Dispatch(msg.payload);
                }

                if (msg.type == "console")
                {
                    EventManager.InvokeConsole(msg.payload);
                }

                if (msg.type == "consoleStatus")
                {
                    EventManager.InvokeConsoleStatus(msg.payload);
                }

                if (msg.type == "view")
                {
                    EventManager.InvokeViewChange(msg.payload);
                }

                if (msg.type == "serverEvent")
                {
                    if (msg.payload == "endMarkerConfig")
                    {
                        EventManager.InvokeServerEventEndMarkerConfig();
                    }
                }
            }
        }
    }
Beispiel #25
0
 public ReferenceCountedMessage Receive()
 {
     return(received.Dequeue());
 }
		protected void RunStep(Stopwatch stopWatch)
		{
			Thread.CurrentThread.CurrentCulture = _currentCulture;
			PauseWait();
			if (Status == CoroutineThreadStatus.Stopped) return;
			stopWatch.Reset();
			stopWatch.Start();
			foreach (var coroutineToAdd in _coroutinesQueue.Dequeue())
			{
				coroutineToAdd.Thread = this;
				coroutineToAdd.ShouldTerminate = false;
				_coroutines.Add(new CoroutineStatus { Instance = coroutineToAdd });
				_startedCoroutines.Increment();
			}
			for (int i = (_coroutines.Count - 1); i >= 0; i--)
			{
				PauseWait();

				var coroutineStatus = _coroutines[i];
				var coroutine = coroutineStatus.Instance;


				try
				{
					// ReSharper disable PossibleMultipleEnumeration
					if (coroutineStatus.Enumerator == null)
					{
						coroutineStatus.Enumerator = new CoroutineStack(coroutine.Run().GetEnumerator(), coroutine);
					}
					if (!coroutineStatus.Enumerator.MoveNext())
					{
						coroutine.ShouldTerminate = true;
					}
					// ReSharper restore PossibleMultipleEnumeration
				}
				catch (Exception ex)
				{
					if (HandleError != null)
					{
						try
						{
							HandleError(ex, coroutine);
						}
						catch (Exception)
						{

						}
					}
					coroutine.OnError(ex);
					if (coroutineStatus.Enumerator != null)
					{
						coroutineStatus.Enumerator.Reset();
					}
					coroutineStatus.Enumerator = null;
				}
				if (coroutine.ShouldTerminate)
				{
					_terminatedCoroutines.Increment();
					_coroutines.RemoveAt(i);
					// ReSharper disable once RedundantAssignment
					coroutine = null;
				}
			}
			stopWatch.Stop();
			var wait = (int)(CycleMaxMs - stopWatch.ElapsedMilliseconds);
			Thread.Sleep(wait > 1 ? wait : 0);
		}
        /// <summary>
        /// Continues to get more information about recipients after all information about endpoints is loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="recipientIdentities"></param>
        /// <param name="loadedEndpoints"></param>
        /// <param name="callback"></param>
        private void GetRecipientInfos(
            IUserOrGroup sender,
            bool forceRefresh,
            HashSet<string> recipientIdentities, 
            LockFreeQueue<Endpoints> loadedEndpoints,
            ParticleEndpoint particleEndpoint,
            Action<EndpointInfo> callback,
            Action<IEnumerable<string>> errorCallback,
            Action<Exception> exceptionCallback)
        {
            try
            {
                // All of the unique particle endpoints, with the recipients at each
                Dictionary<string, List<string>> recipientsAtEndpoints = new Dictionary<string, List<string>>();
                Dictionary<string, string> establishTrustEndpoints = new Dictionary<string, string>();
                Dictionary<string, string> requestedEndpoints = new Dictionary<string, string>();

                Endpoints particleEndpoints;
                while (loadedEndpoints.Dequeue(out particleEndpoints))
                {
                    string endpoint;
                    if (particleEndpoints.TryGetEndpoint(particleEndpoint, out endpoint))
                    {
                        List<string> users;
                        if (recipientsAtEndpoints.TryGetValue(particleEndpoints[ParticleEndpoint.ReceiveNotification], out users))
                            users.Add(particleEndpoints.OpenIdOrWebFinger);
                        else
                        {
                            users = new List<string>();
                            users.Add(particleEndpoints.OpenIdOrWebFinger);

                            recipientsAtEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = users;
                            establishTrustEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = particleEndpoints[ParticleEndpoint.EstablishTrust];
                            requestedEndpoints[particleEndpoints[ParticleEndpoint.ReceiveNotification]] = particleEndpoints[particleEndpoint];
                        }
                    }
                }

                if (!forceRefresh)
                {
                    // Load for situations where trust is already established
                    // copy is to avoid locked the database
                    this.persistedUserManagerData.Read(userManagerData =>
                    {
                        var recipientUser = userManagerData.GetUser(sender.Id);

                        foreach (var recipientAndToken in recipientUser.receiveNotificationEndpointsBySenderToken.Where(
                            r => recipientsAtEndpoints.ContainsKey(r.Value)))
                        {
                            var receiveNotificationEndpoint = recipientAndToken.Value;
                            var senderToken = recipientAndToken.Key;

                            string endpoint;
                            if (requestedEndpoints.TryGetValue(receiveNotificationEndpoint, out endpoint))
                            {
                                var recipientInfo = new EndpointInfo()
                                {
                                    RecipientIdentities = recipientsAtEndpoints[receiveNotificationEndpoint],
                                    Endpoint = endpoint,
                                    SenderToken = senderToken
                                };

                                recipientsAtEndpoints.Remove(receiveNotificationEndpoint);

                                callback(recipientInfo);
                            }
                        }
                    });
                }

                // For situations where trust isn't established, establish trust and then use the callback
                foreach (KeyValuePair<string, List<string>> endpointAndRecipients in recipientsAtEndpoints)
                    GetRecipientInfos(
                        sender,
                        endpointAndRecipients.Key,
                        establishTrustEndpoints[endpointAndRecipients.Key],
                        endpointAndRecipients.Value,
                        requestedEndpoints[endpointAndRecipients.Key],
                        callback,
                        errorCallback);
            }
            catch (Exception e)
            {
                exceptionCallback(e);
            }
        }
Beispiel #28
0
        private static void QueueLevel2()
        {
            try
            {
                while (true)
                {
                    var byteBuffer = lockFreeQueue.Dequeue();

                    //if (byteBuffer != null)
                    //{
                    //    //Console.WriteLine(byteBuffer.ReferenceCount);
                    //    byteBuffer.Release();
                    //}
                    //else
                    //{
                    //    Console.WriteLine("空对象");
                    //}


                    if (byteBuffer != null)
                    {
                        int msgType = byteBuffer.ReadInt();//4
                        if (msgType == 300192)
                        {
                            int    bodyLength       = byteBuffer.ReadInt();                           //4
                            int    channelNo        = byteBuffer.ReadShort();                         //频道代码//2
                            long   applSeqNum       = byteBuffer.ReadLong();                          //消息记录号 从 1开始计数 //8
                            string mdStreamID       = byteBuffer.ReadString(3, Encoding.UTF8).Trim(); //行情类别3
                            string securityID       = byteBuffer.ReadString(8, Encoding.UTF8).Trim(); //证券代码8
                            string securityIDSource = byteBuffer.ReadString(4, Encoding.UTF8).Trim(); //证券代码源4


                            double price        = byteBuffer.ReadLong();                          //8
                            double orderQty     = byteBuffer.ReadLong();                          //8
                            string side         = byteBuffer.ReadString(1, Encoding.UTF8).Trim(); //1
                            long   transactTime = byteBuffer.ReadLong();                          //8
                            string ordType      = byteBuffer.ReadString(1, Encoding.UTF8).Trim(); //扩展字段-订单类型1

                            var msg = new Msg300192_011()
                            {
                                ChannelNo        = channelNo,
                                ApplSeqNum       = applSeqNum,
                                MdStreamID       = mdStreamID,
                                SecurityID       = securityID,
                                SecurityIDSource = securityIDSource,
                                Price            = price,
                                OrderQty         = orderQty,
                                Side             = side,
                                TransactTime     = transactTime,
                            };

                            if (securityID.StartsWith("00") || securityID.StartsWith("30"))
                            {
                                //cjdThread.Start(msg);
                                string tradeDay = transactTime.ToString().Substring(0, 8);


                                //主力资金
                                //60000股||20万元
                                if ((orderQty / 100.0 >= 60000.0 || (price / 10000.0 * orderQty / 100.0) >= 200000.0))
                                {
                                    if (zl.ContainsKey(applSeqNum))
                                    {
                                        zl[applSeqNum] = msg;
                                        //Console.WriteLine(zl[applSeqNum].ApplSeqNum + "|" + zl[applSeqNum].SecurityID + "|" + zl[applSeqNum].OrderQty + "|" + zl[applSeqNum].Price);
                                        //Console.WriteLine(msg.ApplSeqNum + "|" + msg.SecurityID + "|" + msg.OrderQty + "|" + msg.Price);
                                        //Console.WriteLine("----------------");
                                    }
                                    else
                                    {
                                        zl.Add(applSeqNum, msg);
                                    }

                                    // redis.HashSetAsync("zlwt_" + tradeDay + "_" + securityID, applSeqNum.ToString(), msg);//单只股票委托记录
                                    _ = redis.HashIncrementAsync("zlwt_" + tradeDay, securityID);
                                }


                                //闪电单 市价委托&& 60000股||20万元
                                if (ordType == "1" && (orderQty / 100.0 >= 60000.0 || (price / 10000.0 * orderQty / 100.0) >= 200000.0))
                                {
                                    _ = redis.HashSetAsync("wt_" + tradeDay + "_sdd_" + securityID, applSeqNum.ToString(), msg);//委托记录
                                    if (side == "1")
                                    {
                                        sddBuy.Add(applSeqNum, msg);
                                        _ = redis.HashIncrementAsync("sdd_" + tradeDay + "_buy", securityID);
                                    }
                                    else
                                    {
                                        sddSell.Add(applSeqNum, msg);
                                        _ = redis.HashIncrementAsync("sdd_" + tradeDay + "_sell", securityID);
                                    }
                                }

                                //超级单 9999手
                                if ((orderQty / 10000.0) >= 9999.0)
                                {
                                    // Console.WriteLine(dicBuy.Count);
                                    // Console.WriteLine(applSeqNum + "|" + securityID + "|" + price / 10000 + "|" + orderQty / 10000 + "|" + side + "|" + transactTime);
                                    _ = redis.HashSetAsync("wt_" + tradeDay + "_cjd_" + securityID, applSeqNum.ToString(), msg);//委托记录
                                    if (side == "1")
                                    {
                                        cjdBuy.Add(applSeqNum, msg);
                                        _ = redis.HashIncrementAsync("cjd_" + tradeDay + "_buy", securityID);
                                    }
                                    else
                                    {
                                        cjdSell.Add(applSeqNum, msg);
                                        _ = redis.HashIncrementAsync("cjd_" + tradeDay + "_sell", securityID);
                                    }
                                }
                                ///拖拉机单
                                if (tljdList.Count > 0)
                                {
                                    //金额大于100万单子才选,否则委托号不连续导致不认定为拖拉机单
                                    if (((msg.Price / 10000.0) * (msg.OrderQty / 100.0)) >= 1000000.0)
                                    {
                                        var lastMsg = tljdList[tljdList.Count - 1];
                                        //连续委托中 证券代码、买卖方向、委托数量相同且金额大于100万
                                        if (lastMsg.SecurityID == msg.SecurityID && lastMsg.OrderQty == msg.OrderQty && lastMsg.Side == msg.Side)
                                        {
                                            // Console.WriteLine(applSeqNum + "|" + securityID + "|" + price / 10000.0 + "|" + orderQty / 100.0 + "|" + side + "|" + transactTime);

                                            tljdList.Add(msg);
                                            // Console.WriteLine("tljdList.Count:" + tljdList.Count);
                                        }
                                        else
                                        {
                                            if (tljdList.Count >= 4)
                                            {
                                                string itemSide  = "1";
                                                string itemSecid = "";
                                                foreach (var item in tljdList)
                                                {
                                                    Console.WriteLine(item.ApplSeqNum + "|" + item.SecurityID + "|" + item.Price / 10000.0 + "|" + item.OrderQty / 100.0 + "|" + item.Side + "|" + item.TransactTime);
                                                    itemSide  = item.Side;
                                                    itemSecid = item.SecurityID;
                                                    //委托单存起来
                                                    _ = redis.HashSetAsync("wt_" + tradeDay + "_tljd_" + item.SecurityID, item.ApplSeqNum.ToString(), item);//委托记录
                                                    if (itemSide == "1")
                                                    {
                                                        tljdBuy.Add(item.ApplSeqNum, item);
                                                    }
                                                    else
                                                    {
                                                        tljdSell.Add(item.ApplSeqNum, item);
                                                    }
                                                }
                                                if (itemSide == "1")
                                                {
                                                    _ = redis.HashIncrementAsync("tljd_" + tradeDay + "_buy", itemSecid);
                                                }
                                                else
                                                {
                                                    _ = redis.HashIncrementAsync("tljd_" + tradeDay + "_sell", itemSecid);
                                                }
                                                Console.WriteLine("分割线-------------------------------");
                                            }
                                            tljdList.Clear();
                                            tljdList.Add(msg);
                                        }
                                    }
                                }
                                else
                                {
                                    tljdList.Add(msg);
                                }
                            }
                        }

                        if (msgType == 300191)
                        {
                            int    bodyLength       = byteBuffer.ReadInt();                           //4
                            int    channelNo        = byteBuffer.ReadShort();                         //频道代码//2
                            long   applSeqNum       = byteBuffer.ReadLong();                          //消息记录号 从 1开始计数 //8
                            string mdStreamID       = byteBuffer.ReadString(3, Encoding.UTF8).Trim(); //行情类别3
                            long   bidApplSeqNum    = byteBuffer.ReadLong();                          //买方委托索引8
                            long   offerApplSeqNum  = byteBuffer.ReadLong();                          //卖方委托索引8
                            string securityID       = byteBuffer.ReadString(8, Encoding.UTF8).Trim(); //证券代码8
                            string securityIDSource = byteBuffer.ReadString(4, Encoding.UTF8).Trim(); //证券代码源4


                            double lastPx       = byteBuffer.ReadLong();                          //8
                            double lastQty      = byteBuffer.ReadLong();                          //8
                            string execType     = byteBuffer.ReadString(1, Encoding.UTF8).Trim(); //1
                            long   transactTime = byteBuffer.ReadLong();                          //8

                            //var msg = new Msg300191_011()
                            //{
                            //    ChannelNo = channelNo,
                            //    MdStreamID = mdStreamID,
                            //    ApplSeqNum = applSeqNum,
                            //    BidApplSeqNum = bidApplSeqNum,
                            //    OfferApplSeqNum = offerApplSeqNum,
                            //    SecurityID = securityID,
                            //    SecurityIDSource = securityIDSource,
                            //    LastPx = lastPx,
                            //    LastQty = lastQty,
                            //    ExecType = execType,
                            //    TransactTime = transactTime,
                            //};

                            if ((securityID.StartsWith("00") || securityID.StartsWith("30")) && execType == "F")
                            {
                                string tradeDay = transactTime.ToString().Substring(0, 8);
                                string cjTime   = transactTime.ToString();//成交时间
                                double qtyPri   = lastPx * lastQty;


                                bool zlBuy = false;
                                ///主力资金
                                if (zl.ContainsKey(bidApplSeqNum))//买委托单
                                {
                                    var obj = zl[bidApplSeqNum];
                                    if (obj.SecurityID == securityID)
                                    {
                                        zlBuy = true;

                                        //成交金额累加
                                        //  Console.WriteLine(bidApplSeqNum);
                                        // redis.HashIncrementAsync("zlcj_" + tradeDay + "_buy_" + securityID, zl[bidApplSeqNum].ApplSeqNum.ToString(), qtyPri);
                                        _ = redis.HashIncrementAsync("zlcj_" + tradeDay, securityID, qtyPri);  //主力成交
                                        _ = redis.HashIncrementAsync("zljmr_" + tradeDay, securityID, qtyPri); //主力净买入
                                        if (obj.OrderQty == lastQty)                                           //委托数量等于成交数量
                                        {
                                            zl.Remove(bidApplSeqNum);
                                        }
                                    }
                                }
                                ///主力资金
                                if (zl.ContainsKey(offerApplSeqNum))//卖委托单
                                {
                                    var obj = zl[offerApplSeqNum];
                                    if (obj.SecurityID == securityID)
                                    {
                                        // Console.WriteLine(offerApplSeqNum);
                                        //成交金额累加
                                        // redis.HashIncrementAsync("zlcj_" + tradeDay + "_sell_" + securityID, zl[offerApplSeqNum].ApplSeqNum.ToString(), qtyPri);
                                        if (!zlBuy)
                                        {
                                            //一只股票买单已经算过,卖单主力成交就不要再算一遍了
                                            _ = redis.HashIncrementAsync("zlcj_" + tradeDay, securityID, qtyPri); //主力成交
                                        }
                                        _ = redis.HashDecrementAsync("zljmr_" + tradeDay, securityID, qtyPri);    //主力净买入,减去卖单
                                        if (obj.OrderQty == lastQty)                                              //委托数量等于成交数量
                                        {
                                            zl.Remove(offerApplSeqNum);
                                        }
                                    }
                                }


                                //*************************/超级单


                                if (cjdBuy.ContainsKey(bidApplSeqNum))//买委托单
                                {
                                    var obj = cjdBuy[bidApplSeqNum];
                                    if (obj.SecurityID == securityID)
                                    {
                                        // Console.WriteLine(qtyPri);
                                        //成交单在超级委托里面
                                        //  Console.WriteLine(bidApplSeqNum + "|" + dicBuy[bidApplSeqNum].OrderQty + "|" + lastPx + "|" + lastQty + "|" + execType + "|" + applSeqNum);
                                        //成交金额累加
                                        _ = redis.HashIncrementAsync("cjd_" + tradeDay + "_buy_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime, //委托时间
                                            CjTime     = cjTime,
                                            WtSide     = obj.Side,         //
                                            WtSeqNum   = bidApplSeqNum,    //委托单号
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        // redis.HashSet("list_cjd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_cjd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }
                                if (cjdSell.ContainsKey(offerApplSeqNum))//卖委托单
                                {
                                    var obj = cjdSell[offerApplSeqNum];
                                    if (obj.SecurityID == securityID)
                                    {
                                        // Console.WriteLine(qtyPri);
                                        //成交单在超级委托里面
                                        // Console.WriteLine(offerApplSeqNum + "|" + dicSell[offerApplSeqNum].OrderQty + "|" + lastPx + "|" + lastQty + "|" + execType + "|" + applSeqNum);
                                        _ = redis.HashIncrementAsync("cjd_" + tradeDay + "_sell_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime,//委托时间
                                            CjTime     = transactTime,
                                            WtSide     = obj.Side,
                                            WtSeqNum   = offerApplSeqNum,
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        //redis.HashSet("list_cjd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_cjd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }



                                //*************************/闪电单
                                if (sddBuy.ContainsKey(bidApplSeqNum))//买委托单
                                {
                                    var obj = sddBuy[bidApplSeqNum];
                                    // Console.WriteLine(qtyPri);
                                    //成交单在闪电单委托里面
                                    if (obj.SecurityID == securityID)
                                    {
                                        _ = redis.HashIncrementAsync("sdd_" + tradeDay + "_buy_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime,//委托时间
                                            CjTime     = transactTime,
                                            WtSide     = obj.Side,
                                            WtSeqNum   = bidApplSeqNum,
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        //  redis.HashSet("list_sdd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_sdd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }

                                if (sddSell.ContainsKey(offerApplSeqNum))//卖委托单
                                {
                                    var obj = sddSell[offerApplSeqNum];
                                    // Console.WriteLine(qtyPri);
                                    //成交单在闪电单委托里面
                                    if (obj.SecurityID == securityID)
                                    {
                                        _ = redis.HashIncrementAsync("sdd_" + tradeDay + "_sell_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime,//委托时间
                                            CjTime     = transactTime,
                                            WtSide     = obj.Side,
                                            WtSeqNum   = offerApplSeqNum,
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        //redis.HashSet("list_sdd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_sdd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }



                                //*************************/拖拉机单

                                if (tljdBuy.ContainsKey(bidApplSeqNum))//买委托单
                                {
                                    //还要判断证券代码是否变化,否则 已经撤单,委托号变为其他股票的委托
                                    var obj = tljdBuy[bidApplSeqNum];
                                    if (obj.SecurityID == securityID)
                                    {
                                        _ = redis.HashIncrementAsync("tljd_" + tradeDay + "_buy_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime,//委托时间
                                            CjTime     = transactTime,
                                            WtSide     = obj.Side,
                                            WtSeqNum   = bidApplSeqNum,
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        //redis.HashSet("list_tljd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_tljd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }


                                if (tljdSell.ContainsKey(offerApplSeqNum))//卖委托单
                                {
                                    var obj = tljdSell[offerApplSeqNum];

                                    if (obj.SecurityID == securityID)
                                    {
                                        _ = redis.HashIncrementAsync("tljd_" + tradeDay + "_sell_pri", securityID, qtyPri);

                                        var msg = new
                                        {
                                            SecurityID = securityID,
                                            WtTime     = obj.TransactTime,//委托时间
                                            CjTime     = transactTime,
                                            WtSide     = obj.Side,
                                            WtSeqNum   = offerApplSeqNum,
                                            WtPx       = obj.Price,
                                            WtQty      = obj.OrderQty,
                                            CjPx       = lastPx,
                                            CjQty      = lastQty,
                                        };
                                        // redis.HashSet("list_tljd_" + tradeDay, tradeTime, msg);
                                        _ = redis.HashSetAsync("cj_" + tradeDay + "_tljd_" + securityID, applSeqNum.ToString(), msg);//成交记录
                                    }
                                }
                            }
                        }

                        if (msgType == 300111)
                        {
                            int    bodyLength = byteBuffer.ReadInt();                           //4
                            long   origTime   = byteBuffer.ReadLong();                          //数据生成时间8
                            int    channelNo  = byteBuffer.ReadShort();                         //频道代码//2
                            string mdStreamID = byteBuffer.ReadString(3, Encoding.UTF8).Trim(); //行情类别3
                            string securityID = byteBuffer.ReadString(8, Encoding.UTF8).Trim(); //证券代码8

                            if (securityID.StartsWith("00") || securityID.StartsWith("30"))
                            {
                                string securityIDSource = byteBuffer.ReadString(4, Encoding.UTF8).Trim(); //证券代码源4
                                string tradingPhaseCode = byteBuffer.ReadString(8, Encoding.UTF8).Trim(); //交易状态8
                                double prevClose        = byteBuffer.ReadLong();                          //8 昨收盘
                                double numTrades        = byteBuffer.ReadLong();                          //8  成交笔数
                                double totalVolumeTrade = byteBuffer.ReadLong();                          //8 成交总量 2位小数
                                double totalValueTrade  = byteBuffer.ReadLong();                          //8 成交总金额 4位小数

                                var obj = new
                                {
                                    origTime,
                                    securityID,
                                    tradingPhaseCode,
                                    prevClose,
                                    numTrades,
                                    totalVolumeTrade,
                                    totalValueTrade,
                                };
                                _ = redis.StringSetAsync("gghq_" + securityID, obj);
                                //Console.WriteLine(origTime + "|" + channelNo + "|" + mdStreamID + "|" + tradingPhaseCode + "|" + prevClose + "|" + totalVolumeTrade);
                            }
                        }


                        if (msgType == 3)
                        {
                            // Console.WriteLine(msgType);
                        }
                        if (msgType == 1)//登录成功返回的消息
                        {
                            //int bodyLength = byteBuffer.ReadInt();

                            //string senderCompID = byteBuffer.ReadString(20, Encoding.UTF8);
                            //string targetCompID = byteBuffer.ReadString(20, Encoding.UTF8);
                            //int heartBtInt = byteBuffer.ReadInt();
                            //string password = byteBuffer.ReadBytes(16).ToString(Encoding.UTF8);
                            //string defaultApplVerID = byteBuffer.ReadBytes(32).ToString(Encoding.UTF8);
                            //int checkSum = byteBuffer.ReadInt();

                            //Console.WriteLine(msgType+" "+bodyLength + " " + senderCompID + " " + password + " " + checkSum);
                        }


                        byteBuffer.Release();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取队列数据:" + ex.Message);
            }
        }
Beispiel #29
0
        static void TestBufferPool()
        {
            bool console = Interlocked.Increment(ref count) == 1;

            Thread.Sleep(100);

            Item[] dequeued = new Item[actions];

            int   start         = Environment.TickCount;
            int   actionPower   = 24;
            Int64 actionPowered = 1 << actionPower;

            while (run)
            {
                for (int i = 0; i < dequeued.Length; i++)
                {
                    if (testPool)
                    {
                        dequeued[i] = pool.Get();
                    }
                    else
                    {
                        int index = queue.Dequeue();
                        dequeued[i]        = array[index].Value;
                        array[index].Value = null;
                        stack.Push(index);
                    }
                }

                for (int i = 0; i < dequeued.Length; i++)
                {
                    if (items[dequeued[i].TestIndex])
                    {
                        Console.WriteLine(@"Error");
                    }
                    else
                    {
                        items[dequeued[i].TestIndex] = true;
                    }
                }

                for (int i = 0; i < dequeued.Length; i++)
                {
                    items[dequeued[i].TestIndex] = false;
                }

                for (int i = 0; i < dequeued.Length; i++)
                {
                    if (testPool)
                    {
                        pool.Put(dequeued[i]);
                    }
                    else
                    {
                        int index = stack.Pop();
                        array[index].Value = dequeued[i];
                        queue.Enqueue(index);
                    }

                    Interlocked.Increment(ref actionCount);
                }

                if (console)
                {
                    if (actionPowered < actionCount)
                    {
                        int    ms    = Environment.TickCount - start;
                        double speed = (double)Thread.VolatileRead(ref actionCount) / (double)ms;
                        Console.WriteLine("Reach 2 ^ {0}: {1} ms, {2:0.00} per/ms", actionPower, ms, speed);
                        actionPower++;
                        actionPowered <<= 1;
                    }
                }
            }

            Interlocked.Decrement(ref count);
        }