コード例 #1
0
        private void PrepareQueueData(LockFreeQueue <int> queue, int dataCount)
        {
            int seed = 0;

            for (int j = 0; j < dataCount; j++)
            {
                queue.Enqueue(Interlocked.Increment(ref seed));
            }
        }
コード例 #2
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]);
        }
コード例 #3
0
 public static void ProducerThread()
 {
     while (_toSendElements > Interlocked.Read(ref _sentElements))
     {
         if (Interlocked.Increment(ref _sentElements) <= _toSendElements)
         {
             _internalQueue.Enqueue(new CollectionElement(0));
         }
     }
 }
コード例 #4
0
 static RequestObjectMessage()
 {
     _resetEvents = new LockFreeQueue<ManualResetEventSlim>();
     int count = 100;
     while (count >= 0)
     {
         _resetEvents.Enqueue(new ManualResetEventSlim(false));
         count--;
     }
 }
コード例 #5
0
ファイル: BufferManager.cs プロジェクト: 745c5412/Stump
        /// <summary>
        ///     Requeues a segment into the buffer pool.
        /// </summary>
        /// <param name="segment">the segment to requeue</param>
        public void CheckIn(BufferSegment segment)
        {
            if (segment.Uses > 1)
            {
#if DEBUG
                log.Error(
                    "Checked in segment (Size: {0}, Number: {1}, Uses:{5}) that is already in use! Queue contains: {2}, Buffer amount: {3} Last Usage:{4}, StackTrace:{6}",
                    segment.Length, segment.Number, m_availableSegments.Count, m_buffers.Count, segment.LastUserTrace, segment.Uses, new StackTrace().ToString());
#else
                log.Error(
                    "Checked in segment (Size: {0}, Number: {1}, Uses:{4}) that is already in use! Queue contains: {2}, Buffer amount: {3}, StackTrace:{5}",
                    segment.Length, segment.Number, m_availableSegments.Count, m_buffers.Count, segment.Uses, new StackTrace().ToString());
#endif
            }

            m_availableSegments.Enqueue(segment);

            BufferSegment dummy;
            m_segmentsInUse.TryRemove(segment.Number, out dummy);
        }
コード例 #6
0
            public override void Start(SocketState ss)
            {
                DateTime now = DateTime.UtcNow;

                if (now - _last_debug > _debug_period)
                {
                    _last_debug = now;
                    ProtocolLog.Write(ProtocolLog.Monitor, String.Format("I am alive: {0}", now));
                }
                //Run ourselves again later.
                _q.Enqueue(this);
            }
コード例 #7
0
        /* //////////////////////////////
         *
         * Here are all the normal methods of TcpEdgeListener
         *
         * //////////////////////////////
         */


        public override void CreateEdgeTo(TransportAddress ta, EdgeCreationCallback ecb)
        {
            try {
                if (!IsStarted)
                {
                    throw new EdgeException("TcpEdgeListener is not started");
                }
                else if (ta.TransportAddressType != TransportAddress.TAType.Tcp)
                {
                    throw new EdgeException(ta.TransportAddressType.ToString()
                                            + " is not my type: Tcp");
                }
                else if (_ta_auth.Authorize(ta) == TAAuthorizer.Decision.Deny)
                {
                    //Too bad.  Can't make this edge:
                    throw new EdgeException(ta.ToString() + " is not authorized");
                }
                else
                {
                    //Everything looks good:
                    ArrayList tmp_ips = new ArrayList();
                    tmp_ips.Add(((IPTransportAddress)ta).GetIPAddress());
                    CreationState cs = new CreationState(ecb,
                                                         new Queue(tmp_ips),
                                                         ((IPTransportAddress)ta).Port,
                                                         this);
                    ActionQueue.Enqueue(cs);
                }
            } catch (Exception e) {
                ecb(false, null, e);
            }
        }
コード例 #8
0
 public void ItShouldBePossibleToClearAQueueAndDequeueASingleItem()
 {
     var lfq = new LockFreeQueue<string>();
     var lele = new List<string>();
     for (int i = 0; i < ENQUEUED_DATA; i++)
     {
         lele.Add("TEST_" + i);
     }
     lfq.Enqueue(lele);
     Assert.AreEqual("TEST_0", lfq.DequeueSingle());
     lfq.Clear();
     Assert.IsNull(lfq.DequeueSingle());
 }
コード例 #9
0
ファイル: WebRtcDataChannel.cs プロジェクト: unitycoder/ubiq
 public void OnMessage(bool binary, IntPtr data, int size)
 {
     if (binary)
     {
         var msg = pool.Rent(size);
         Marshal.Copy(data, msg.bytes, msg.start, size);
         received.Enqueue(msg);
     }
     else
     {
         Debug.LogException(new NotImplementedException());
     }
 }
コード例 #10
0
        public void AllTest()
        {
            int seed = 0;

            Thread[]            producerThreads = new Thread[this.m_threadCount];
            Thread[]            consumerThreads = new Thread[this.m_threadCount];
            LockFreeQueue <int> queue           = new LockFreeQueue <int>();

            for (int i = 0; i < this.m_threadCount; i++)
            {
                producerThreads[i] = new Thread(() => {
                    for (int j = 0; j < this.m_dataCount; j++)
                    {
                        queue.Enqueue(Interlocked.Increment(ref seed));
                    }
                });
            }
            for (int i = 0; i < this.m_threadCount; i++)
            {
                consumerThreads[i] = new Thread(() => {
                    int value = 0;
                    for (int j = 0; j < this.m_dataCount;)
                    {
                        if (queue.TryDequeue(out value))
                        {
                            Assert.AreNotEqual(0, value);

                            j++;
                        }
                        else
                        {
                            Thread.Sleep(1);
                        }
                    }
                });
            }

            for (int i = 0; i < this.m_threadCount; i++)
            {
                producerThreads[i].Start();
                consumerThreads[i].Start();
            }

            for (int i = 0; i < this.m_threadCount; i++)
            {
                producerThreads[i].Join();
                consumerThreads[i].Join();
            }

            Assert.AreEqual(0, queue.Count);
        }
コード例 #11
0
 public void Add(T item)
 {
     _requestsQueue.Enqueue(new AsyncCollectionRequest <T>
     {
         Data      = item,
         EventType = AsyncCollectionEventType.Add
     });
 }
コード例 #12
0
 public void ItShouldBePossibleToEnqueuAndDequeuNonNullableElements()
 {
     var lfq = new LockFreeQueue<int>();
     var lele = new List<int>();
     for (int i = 0; i < ENQUEUED_DATA; i++)
     {
         lele.Add(i);
     }
     lfq.Enqueue(lele);
     Assert.AreEqual(0, lfq.DequeueSingle());
     lfq.Clear();
     Assert.AreEqual(0,lfq.Count);
     Assert.AreEqual(0,lfq.DequeueSingle());
 }
コード例 #13
0
        public void LockFreeQueueIntItShouldBePossibleToClearAQueueAndDequeueASingleItem()
        {
            var lfq  = new LockFreeQueue <string>();
            var lele = new List <string>();

            for (int i = 0; i < ENQUEUED_DATA; i++)
            {
                lele.Add("TEST_" + i);
            }
            lfq.Enqueue(lele);
            Assert.AreEqual("TEST_0", lfq.DequeueSingle());
            lfq.Clear();
            Assert.IsNull(lfq.DequeueSingle());
        }
コード例 #14
0
        private void OnLogMessage(string condition, string stackTrace, LogType type)
        {
            string logType;

            switch (type)
            {
            case LogType.Log:
                logType = "info";
                break;

            case LogType.Warning:
                logType = "warning";
                break;

            case LogType.Error:
            case LogType.Exception:
                logType = "error";
                break;

            case LogType.Assert:
            default:
                logType = "debug";
                break;
            }

            var msg = condition;

            if (type == LogType.Error || type == LogType.Exception)
            {
                msg += "\n" + stackTrace;
            }

            _messages.Enqueue(new LogMsg(logType, msg));

            // start sendMessages timer
            _msgSubject.OnNext(0);
        }
コード例 #15
0
        /// <summary>
        ///     Dequeues the work item.
        /// </summary>
        /// <param name="singleThreadRunner">The single thread runner.</param>
        /// <param name="isGetNewOne">
        ///     if set to <c>true</c> [is get new one].
        /// </param>
        /// <param name="returnedWorkItem">The returned work item.</param>
        /// <returns>
        ///     <see langword="true" />, if a work item has been
        ///     successfully dequeued. <see langword="false" /> otherwise.
        /// </returns>
        internal WorkItem DequeueWorkItemInternal(SingleThreadRunner singleThreadRunner, bool isGetNewOne,
                                                  WorkItem returnedWorkItem = null)
        {
            if (returnedWorkItem != null)
            {
                returnedWorkItems.Enqueue(returnedWorkItem);
            }

            if (!shutDownSignaled && isGetNewOne)
            {
                var workItem = workItemQueue.Dequeue();
                if (workItem != null)
                {
                    workItem.SingleThreadRunner = singleThreadRunner;
                    return(workItem);
                }
            }

            // If we are here, there is no more work to do left...
            // The worker has to be set to idle...
            Interlocked.Decrement(ref threadsWorking);
            threadsIdle.Enqueue(singleThreadRunner);
            return(null);
        }
コード例 #16
0
        public void LockFreeQueueDequeue()
        {
            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);
            //For each number enqueued we check that is removed properly and in the
            //queue order (FIFO)
            Assert.AreEqual(queue.DequeueSingle(), 1);
            Assert.AreEqual(queue.Count, 4);
            Assert.AreEqual(queue.DequeueSingle(), 2);
            Assert.AreEqual(queue.Count, 3);
            Assert.AreEqual(queue.DequeueSingle(), 3);
            Assert.AreEqual(queue.Count, 2);
            Assert.AreEqual(queue.DequeueSingle(), 4);
            Assert.AreEqual(queue.Count, 1);
            Assert.AreEqual(queue.DequeueSingle(), 5);
            Assert.AreEqual(queue.Count, 0);
            Assert.AreEqual(default(int), queue.DequeueSingle());
        }
コード例 #17
0
        public void LockFreeQueueIntItShouldBePossibleToEnqueuAndDequeuNonNullableElements()
        {
            var lfq  = new LockFreeQueue <int>();
            var lele = new List <int>();

            for (int i = 0; i < ENQUEUED_DATA; i++)
            {
                lele.Add(i);
            }
            lfq.Enqueue(lele);
            Assert.AreEqual(0, lfq.DequeueSingle());
            lfq.Clear();
            Assert.AreEqual(0, lfq.Count);
            Assert.AreEqual(0, lfq.DequeueSingle());
        }
コード例 #18
0
        /// <summary>
        /// Blocks until events are sent on the session, or timeout is reached, then processes any received events and adds them
        /// to eventQueue. This function implements the new event system, available in API version 1.9.
        /// In the new event system, (GetAllRecords + GetEvents) sequence will replace (RegisterForEvents + DownloadObjects + GetNextEvents).
        /// </summary>
        /// <param name="session"></param>
        /// <param name="eventQueue"></param>
        /// <param name="cancelled"></param>
        /// <param name="legacyEventSystem">True if legacy event system (event.next) should be used.</param>
        /// <param name="token">A token used by event.from().
        /// It should be the empty string when event.from is first called, which is the replacement of get_all_records.
        /// </param>
        public static void GetEvents(Session session, LockFreeQueue <ObjectChange> eventQueue, HTTP.FuncBool cancelled, bool legacyEventSystem, ref string token)
        {
            if (legacyEventSystem)
            {
                GetNextEvents(session, eventQueue, cancelled);
                return;
            }

            Proxy_Event[] proxyEvents;
            try
            {
                var classes     = new [] { "*" }; // classes that we are interested in receiving events from
                var eventResult = Event.from(session, classes, token, EVENT_FROM_TIMEOUT);
                token       = eventResult.token;
                proxyEvents = eventResult.events;
            }
            catch (WebException e)
            {
                // Catch timeout, and turn it into an EventNextBlockedException so we can recognise it later (CA-33145)
                if (e.Status == WebExceptionStatus.Timeout)
                {
                    throw new EventNextBlockedException();
                }
                else
                {
                    throw;
                }
            }

            if (cancelled())
            {
                return;
            }

            //We want to do the marshalling on this bg thread so as not to block the gui thread
            foreach (Proxy_Event proxyEvent in proxyEvents)
            {
                ObjectChange objectChange = ProcessEvent(proxyEvent);

                if (objectChange != null)
                {
                    eventQueue.Enqueue(objectChange);
                }
            }
        }
コード例 #19
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);
            }
        }
コード例 #20
0
        /// <summary>
        /// Blocks until events are sent on the session, then processes any received events and adds them
        /// to eventQueue. Will always add at least one event to eventQueue.
        /// This function should be used with XenServer up to version 6.0. For XenServer higher than 6.0, GetEvents() should be used instead.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="eventQueue"></param>
        /// <param name="cancelled"></param>
        public static void GetNextEvents(Session session, LockFreeQueue <ObjectChange> eventQueue, HTTP.FuncBool cancelled)
        {
            Proxy_Event[] proxyEvents;

            try
            {
                proxyEvents = Event.next(session);
            }
            catch (WebException e)
            {
                // Catch timeout, and turn it into an EventNextBlockedException so we can recognise it later (CA-33145)
                if (e.Status == WebExceptionStatus.Timeout)
                {
                    throw new EventNextBlockedException();
                }
                else
                {
                    throw;
                }
            }

            if (proxyEvents.Length == 0)
            {
                throw new IOException("Event.next() returned no events; the server is misbehaving.");
            }

            if (cancelled())
            {
                return;
            }

            //We want to do the marshalling on this bg thread so as not to block the gui thread
            foreach (Proxy_Event proxyEvent in proxyEvents)
            {
                ObjectChange objectChange = ProcessEvent(proxyEvent);

                if (objectChange != null)
                {
                    eventQueue.Enqueue(objectChange);
                }
            }
        }
コード例 #21
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="ThreadPool" /> class.
        /// </summary>
        public ThreadPool(int numberOfThreads, string threadsNamePrefix)
        {
            NumberOfThreads = numberOfThreads;
            threads         = new Queue <SingleThreadRunner>();
            threadsIdle     = new LockFreeQueue <SingleThreadRunner>();

            // allocate threads...
            for (var i = 0; i < NumberOfThreads; i++)
            {
                var singleThreadRunner = new SingleThreadRunner(this);
                singleThreadRunner.Thread              = new Thread(singleThreadRunner.DoWork);
                singleThreadRunner.Thread.Name         = threadsNamePrefix + (i + 1);
                singleThreadRunner.Thread.IsBackground = true;

                threads.Enqueue(singleThreadRunner);
                threadsIdle.Enqueue(singleThreadRunner);

                singleThreadRunner.Thread.Start();
            }
        }
コード例 #22
0
        /// <sumary>
        /// Gets all objects from the server. Used in order to fill the cache.
        /// This function implements the new event system, available from in API version 1.9.
        /// In the new event system, (GetAllRecords + GetEvents) sequence will replace (RegisterForEvents + DownloadObjects + GetNextEvents).
        /// </summary>
        /// <param name="session">The session over which to download the objects. Must not be null.</param>
        /// <param name="changes">The queue that the ObjectChanges will be put into. Must not be null.</param>
        /// <param name="cancelled">Used by GetEvents().</param>
        /// <param name="legacyEventSystem">True if legacy event system (event.next) should to be used.</param>
        /// <param name="token">Used by GetEvents().</param>
        public static void GetAllObjects(Session session, LockFreeQueue <ObjectChange> changes, HTTP.FuncBool cancelled, bool legacyEventSystem, ref string token)
        {
            if (legacyEventSystem)
            {
                DownloadObjects(session, changes);
                return;
            }

            // download objects that are not covered by event.from(), e.g. Roles
            List <ObjectChange> list = new List <ObjectChange>();

            Download_Role(session, list);
            foreach (ObjectChange o in list)
            {
                changes.Enqueue(o);
            }

            // get all objects with event.from()
            token = "";
            GetEvents(session, changes, cancelled, false, ref token);
        }
コード例 #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);
            }
        }
コード例 #24
0
    async void GetStuff(ClientWebSocket cws)
    {
        try
        {
            if (cws.State == WebSocketState.Open || cws.State == WebSocketState.CloseSent)
            {
                WebSocketReceiveResult r = await cws.ReceiveAsync(buf, CancellationToken.None);

                queue.Enqueue(Encoding.UTF8.GetString(buf.Array, 0, r.Count));
                GetStuff(cws);
            }
        }
        catch (WebSocketException e)
        {
            Debug.LogException(e);
            cws.Abort();
            connected = false;
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            connected = false;
        }
    }
コード例 #25
0
        // TODO
        // A lot of the logic in this file that's not tied to the DB should move someplace else so that independent implementations can use it
        /// <summary>
        /// Gets information about recipients for sending a notification
        /// </summary>
        /// <param name="openIdOrWebFinger"></param>
        /// <param name="forceRefresh"></param>
        /// <returns></returns>
        public void GetEndpointInfos(
            IUserOrGroup sender,
            bool forceRefresh, 
            IEnumerable<string> recipientIdentitiesArg,
            ParticleEndpoint particleEndpoint,
            Action<EndpointInfo> callback,
            Action<IEnumerable<string>> errorCallback,
            Action<Exception> exceptionCallback)
        {
            HashSet<string> recipientIdentities = new HashSet<string>(recipientIdentitiesArg);

            long outstandingRequests = recipientIdentities.Count;

            LockFreeQueue<Endpoints> loadedEndpoints = new LockFreeQueue<Endpoints>();

            Action<Endpoints> endpointLoaded = delegate(Endpoints endpoints)
            {
                loadedEndpoints.Enqueue(endpoints);

                if (0 == Interlocked.Decrement(ref outstandingRequests))
                    GetRecipientInfos(sender, forceRefresh, recipientIdentities, loadedEndpoints, particleEndpoint, callback, errorCallback, exceptionCallback);
            };

            Action<Exception> endpointException = delegate(Exception e)
            {
                if (0 == Interlocked.Decrement(ref outstandingRequests))
                    GetRecipientInfos(sender, forceRefresh, recipientIdentities, loadedEndpoints, particleEndpoint, callback, errorCallback, exceptionCallback);
            };

            foreach (string openIdOrWebFinger in recipientIdentities)
                Endpoints.GetEndpoints(openIdOrWebFinger, forceRefresh, endpointLoaded, endpointException);
        }
コード例 #26
0
        /// <summary>
        /// Downloads all objects from the server. Used in order to fill the cache.
        /// This function should be used with XenServer up to version 6.0. For XenServer higher than 6.0, GetAllObjects() should be used instead.
        /// </summary>
        /// <param name="session">The session over which to download the objects. Must not be null.</param>
        /// <param name="changes">The queue that the ObjectChanges will be put into. Must not be null.</param>
        public static void DownloadObjects(Session session, LockFreeQueue <ObjectChange> changes)
        {
            List <ObjectChange> list = new List <ObjectChange>();

            Download_Task(session, list);
            Download_Pool(session, list);
            Download_VM(session, list);
            Download_VM_metrics(session, list);
            Download_VM_guest_metrics(session, list);
            Download_Host(session, list);
            Download_Host_crashdump(session, list);
            Download_Host_patch(session, list);
            Download_Host_metrics(session, list);
            Download_Host_cpu(session, list);
            Download_Network(session, list);
            Download_VIF(session, list);
            Download_VIF_metrics(session, list);
            Download_PIF(session, list);
            Download_PIF_metrics(session, list);
            Download_SM(session, list);
            Download_SR(session, list);
            Download_VDI(session, list);
            Download_VBD(session, list);
            Download_VBD_metrics(session, list);
            Download_PBD(session, list);
            Download_Crashdump(session, list);
            Download_Console(session, list);

            if (session.APIVersion >= API_Version.API_1_2)
            {
                // Download Miami-only objects
                Download_Pool_patch(session, list);
                Download_Bond(session, list);
                Download_VLAN(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_3)
            {
                // Download Orlando-only objects
                Download_Blob(session, list);
                Download_Message(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_6)
            {
                // Download George-only objects
                Download_Subject(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_7)
            {
                // Download Midnight Ride-only objects
                Download_Role(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_8)
            {
                // Download Cowley-only objects
                Download_VMPP(session, list);
                Download_Tunnel(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_9)
            {
                // Download Boston-only objects
                Download_VM_appliance(session, list);
                Download_DR_task(session, list);
                Download_PCI(session, list);
                Download_PGPU(session, list);
                Download_GPU_group(session, list);
                Download_VGPU(session, list);
            }

            foreach (ObjectChange o in list)
            {
                changes.Enqueue(o);
            }
        }
コード例 #27
0
        /// <summary>
        /// Blocks until events are sent on the session, or timeout is reached, then processes any received events and adds them
        /// to eventQueue. This function implements the new event system, available in API version 1.9. 
        /// In the new event system, (GetAllRecords + GetEvents) sequence will replace (RegisterForEvents + DownloadObjects + GetNextEvents).
        /// </summary>
        /// <param name="session"></param>
        /// <param name="eventQueue"></param>
        /// <param name="cancelled"></param>
        /// <param name="legacyEventSystem">True if legacy event system (event.next) should be used.</param>
        /// <param name="token">A token used by event.from(). 
        /// It should be the empty string when event.from is first called, which is the replacement of get_all_records.
        /// </param>
        public static void GetEvents(Session session, LockFreeQueue<ObjectChange> eventQueue, HTTP.FuncBool cancelled, bool legacyEventSystem, ref string token)
        {
            if (legacyEventSystem)
            {
                GetNextEvents(session, eventQueue, cancelled);
                return;
            }

            Proxy_Event[] proxyEvents;
            try
            {
                var classes = new [] { "*" }; // classes that we are interested in receiving events from
                var eventResult = Event.from(session, classes, token, EVENT_FROM_TIMEOUT);
                token = eventResult.token;
                proxyEvents = eventResult.events;
            }
            catch (WebException e)
            {
                // Catch timeout, and turn it into an EventNextBlockedException so we can recognise it later (CA-33145)
                if (e.Status == WebExceptionStatus.Timeout)
                    throw new EventNextBlockedException();
                else
                    throw;
            }

            if (cancelled())
                return;

            //We want to do the marshalling on this bg thread so as not to block the gui thread
            foreach (Proxy_Event proxyEvent in proxyEvents)
            {
                ObjectChange objectChange = ProcessEvent(proxyEvent);

                if (objectChange != null)
                    eventQueue.Enqueue(objectChange);
            }
        }
コード例 #28
0
        /// <sumary>
        /// Gets all objects from the server. Used in order to fill the cache.
        /// This function implements the new event system, available from in API version 1.9.
        /// In the new event system, (GetAllRecords + GetEvents) sequence will replace (RegisterForEvents + DownloadObjects + GetNextEvents).
        /// </summary>
        /// <param name="session">The session over which to download the objects. Must not be null.</param>
        /// <param name="changes">The queue that the ObjectChanges will be put into. Must not be null.</param>
        /// <param name="cancelled">Used by GetEvents().</param>
        /// <param name="legacyEventSystem">True if legacy event system (event.next) should to be used.</param>
        /// <param name="token">Used by GetEvents().</param>
        public static void GetAllObjects(Session session, LockFreeQueue<ObjectChange> changes, HTTP.FuncBool cancelled, bool legacyEventSystem, ref string token)
        {
            if (legacyEventSystem)
            {
                DownloadObjects(session, changes);
                return;
            }

            // download objects that are not covered by event.from(), e.g. Roles
            List<ObjectChange> list = new List<ObjectChange>();
            Download_Role(session, list);
            foreach (ObjectChange o in list)
                changes.Enqueue(o);

            // get all objects with event.from()
            token = "";
            GetEvents(session, changes, cancelled, false, ref token);
        }
コード例 #29
0
        /// <summary>
        /// Blocks until events are sent on the session, then processes any received events and adds them
        /// to eventQueue. Will always add at least one event to eventQueue.
        /// This function should be used with XenServer up to version 6.0. For XenServer higher than 6.0, GetEvents() should be used instead.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="eventQueue"></param>
        /// <param name="cancelled"></param>
        public static void GetNextEvents(Session session, LockFreeQueue<ObjectChange> eventQueue, HTTP.FuncBool cancelled)
        {
            Proxy_Event[] proxyEvents;

            try
            {
                proxyEvents = Event.next(session);
            }
            catch (WebException e)
            {
                // Catch timeout, and turn it into an EventNextBlockedException so we can recognise it later (CA-33145)
                if (e.Status == WebExceptionStatus.Timeout)
                    throw new EventNextBlockedException();
                else
                    throw;
            }

            if (proxyEvents.Length == 0)
                throw new IOException("Event.next() returned no events; the server is misbehaving.");

            if (cancelled())
                return;

            //We want to do the marshalling on this bg thread so as not to block the gui thread
            foreach (Proxy_Event proxyEvent in proxyEvents)
            {
                ObjectChange objectChange = ProcessEvent(proxyEvent);

                if (objectChange != null)
                    eventQueue.Enqueue(objectChange);
            }
        }
コード例 #30
0
 void ResponderHandle(CKARNetworkState state)
 {
     stateQueue.Enqueue(state);
 }
コード例 #31
0
ファイル: SelfRunningTaskPool.cs プロジェクト: 745c5412/Stump
 public virtual void AddMessage(IMessage message)
 {
     m_messageQueue.Enqueue(message);
 }
コード例 #32
0
ファイル: MainForm.cs プロジェクト: BGCX261/zma-svn-to-git
 private void AppendOutput(string str)
 {
     messageQueue.Enqueue(str);
 }
コード例 #33
0
 public void Push(ref JsonWriter writer)
 {
     events.Enqueue(writer);
     Interlocked.Add(ref Memory, writer.BufferSize);
 }
コード例 #34
0
 public void AddMessage(Action action)
 {
     m_messageQueue.Enqueue(action);
 }
コード例 #35
0
ファイル: Area.cs プロジェクト: Mixi59/Stump
 public void AddMessage(IMessage msg)
 {
     // make sure, Map is running
     // Start();
     m_messageQueue.Enqueue(msg);
 }
コード例 #36
0
 public void CloseHandler(object edge, EventArgs ea)
 {
     _queue.Enqueue(this);
 }
 private void addLq_Action(int item, ParallelLoopState ls)
 {
     lq.Enqueue(rand.Next());
 }
コード例 #38
0
        /// <summary>
        /// Downloads all objects from the server. Used in order to fill the cache.
        /// This function should be used with XenServer up to version 6.0. For XenServer higher than 6.0, GetAllObjects() should be used instead.
        /// </summary>
        /// <param name="session">The session over which to download the objects. Must not be null.</param>
        /// <param name="changes">The queue that the ObjectChanges will be put into. Must not be null.</param>
        public static void DownloadObjects(Session session, LockFreeQueue<ObjectChange> changes)
        {
            List<ObjectChange> list = new List<ObjectChange>();

            Download_Task(session, list);
            Download_Pool(session, list);
            Download_VM(session, list);
            Download_VM_metrics(session, list);
            Download_VM_guest_metrics(session, list);
            Download_Host(session, list);
            Download_Host_crashdump(session, list);
            Download_Host_patch(session, list);
            Download_Host_metrics(session, list);
            Download_Host_cpu(session, list);
            Download_Network(session, list);
            Download_VIF(session, list);
            Download_VIF_metrics(session, list);
            Download_PIF(session, list);
            Download_PIF_metrics(session, list);
            Download_SM(session, list);
            Download_SR(session, list);
            Download_VDI(session, list);
            Download_VBD(session, list);
            Download_VBD_metrics(session, list);
            Download_PBD(session, list);
            Download_Crashdump(session, list);
            Download_Console(session, list);

            if (session.APIVersion >= API_Version.API_1_2)
            {
                // Download Miami-only objects
                Download_Pool_patch(session, list);
                Download_Bond(session, list);
                Download_VLAN(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_3)
            {
                // Download Orlando-only objects
                Download_Blob(session, list);
                Download_Message(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_6)
            {
                // Download George-only objects
                Download_Subject(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_7)
            {
                // Download Midnight Ride-only objects
                Download_Role(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_8)
            {
                // Download Cowley-only objects
                Download_VMPP(session, list);
                Download_Tunnel(session, list);
            }

            if (session.APIVersion >= API_Version.API_1_9)
            {
                // Download Boston-only objects
                Download_VM_appliance(session, list);
                Download_DR_task(session, list);
                Download_PCI(session, list);
                Download_PGPU(session, list);
                Download_GPU_group(session, list);
                Download_VGPU(session, list);
            }

            foreach (ObjectChange o in list)
            {
                changes.Enqueue(o);
            }
        }
コード例 #39
0
        public void GetCommands(MinecraftHandler mc, LockFreeQueue<WebActionCommand> webCommands)
        {
            try
            {
                if (mc.Started && mc.Config.StreamEnabled)
                {
                    String guid = mc.Config.GuidString;

                    MySqlCommand command = connection.CreateCommand();
                    String sql = String.Format(
                        "SELECT * FROM zma_app.zma_web_queue w WHERE w.server_guid = '{0}';"
                        , guid);
                    command.CommandText = sql;
                    MySqlDataReader reader = command.ExecuteReader();
                    List<int> ids = new List<int>();

                    int id = -1;

                    while (reader.Read())
                    {
                        id = reader.GetInt32("id");
                        WebActionType type = WebActionType.None;
                        type = (WebActionType)reader.GetInt32("type");
                        string message = "";
                        message = reader.GetString("message");
                        UserCollectionSingletone users = UserCollectionSingletone.GetInstance();

                        String userName = "";
                        try
                        {
                            userName = reader.GetString("name");
                        }
                        catch
                        {

                        }

                        if (id >= 0)
                        {
                            ids.Add(id);
                        }

                        User user = users.GetUserByName(userName);
                        if (type == WebActionType.Chat && id >= 0 && !user.Generated)
                        {
                            WebActionCommand cmd = new WebActionCommand(id, type, message, user, this);
                            webCommands.Enqueue(cmd);
                        }

                    }

                    reader.Close();

                    foreach (int i in ids)
                    {
                        command.CommandText = String.Format("DELETE FROM zma_app.zma_web_queue WHERE id = {0};", i);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch ( Exception ex)
            {
                Log.Append(this,"GetCommands "+  ex.Message, Log.ExceptionsLog);
            }
        }