static void Main(string[] args)
    {
        var c = new System.Collections.Concurrent.BlockingCollection <Tuple <bool, Action> >();
        var t = new Thread(() =>
        {
            while (true)
            {
                var item = c.Take();
                if (!item.Item1)
                {
                    break;
                }
                item.Item2();
            }
            Console.WriteLine("Exiting thread");
        });

        t.Start();

        Console.WriteLine("Press any key to queue first action");
        Console.ReadKey();
        c.Add(Tuple.Create <bool, Action>(true, () => Console.WriteLine("Executing first action")));

        Console.WriteLine("Press any key to queue second action");
        Console.ReadKey();
        c.Add(Tuple.Create <bool, Action>(true, () => Console.WriteLine("Executing second action")));
        Console.WriteLine("Press any key to stop the thread");
        Console.ReadKey();
        c.Add(Tuple.Create <bool, Action>(false, null));

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
Пример #2
0
        /// <summary>
        /// close recording stream
        /// </summary>
        public void CloseFile()
        {
            threadQ.Add(new Object());             // acts as stop message
            workerT.Join();

            jmdfile.Close();
        }
Пример #3
0
        /// <summary>
        /// 异步入队
        /// </summary>
        /// <param name="queueName">队列名</param>
        /// <param name="dataObj">入队数据</param>
        /// <param name="persistent">数据是否持久化</param>
        /// <param name="durableQueue">队列是否持久化</param>
        public void Send(string queueName, object dataObj, bool persistent = false, bool durableQueue = false)
        {
            if (_queue.Count < _maxQueueCount)
            {
                var qm = new QueueMessage();
                qm.exchangeName = "";
                qm.queueName    = queueName;
                qm.data         = dataObj;
                qm.persistent   = persistent;
                qm.durableQueue = durableQueue;
                qm.exchangeType = ExchangeType.Default;

                _queue.Add(new StrongBox <QueueMessage>(qm));
            }
        }
Пример #4
0
 public void CloseFile()
 {
     threadQ.Add(new object());             // acts as stop message
     workerT.Join();
     _currSegment?.Dispose();
     _currSegment = null;
 }
Пример #5
0
        public RpcClient()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            connection     = factory.CreateConnection();
            channel        = connection.CreateModel();
            replyQueueName = channel.QueueDeclare().QueueName;
            consumer       = new EventingBasicConsumer(channel);

            props = channel.CreateBasicProperties();
            var correlationId = Guid.NewGuid().ToString();

            props.CorrelationId = correlationId;
            props.ReplyTo       = replyQueueName;

            consumer.Received += (model, ea) =>
            {
                var body     = ea.Body;
                var response = Encoding.UTF8.GetString(body);
                if (ea.BasicProperties.CorrelationId == correlationId)
                {
                    respQueue.Add(response);
                }
            };
        }
Пример #6
0
        public static void RegisterJob <T> (Job <T> job)
        {
            if (null == job.action)
            {
                return;
            }

            job.exception = null;

            var j = new Job <object> ()
            {
                action        = () => job.action(),
                callbackError = job.callbackError,
            };

            if (job.callbackSuccess != null)
            {
                j.callbackSuccess = (arg) => job.callbackSuccess((T)arg);
            }
            if (job.callbackFinish != null)
            {
                j.callbackFinish = (arg) => job.callbackFinish((T)arg);
            }

            s_jobs.Add(j);
        }
Пример #7
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            string s = Encoding.UTF8.GetString(buffer, offset, count);

            _texts.Add(s);
            //_texts.CompleteAdding();
        }
Пример #8
0
        private void EnqueueMessage(ConsoleColor newColor, string message, params object[] args)
        {
            if (args.Length > 0)
            {
                message = string.Format(message, args);
            }

            _PendingLogs.Add(Tuple.Create(message, newColor));
        }
Пример #9
0
 public void CloseFile()
 {
     threadQ.Add(new Object());             // acts as stop message
     workerT.Join();
     if (currSegment != null)
     {
         currSegment.Dispose();
     }
     currSegment = null;
 }
Пример #10
0
 private void SafeAddToReinitialiseQueue(T pooledObject)
 {
     try
     {
         if (!_ItemsToInitialise.IsAddingCompleted)
         {
             _ItemsToInitialise.Add(pooledObject);
         }
     }
     catch (InvalidOperationException) { }             //Handle race condition on above if condition.
 }
Пример #11
0
        protected override void HandleDeliveryImpl(IBasicProperties properties, byte[] body)
        {
            lock (m_lockObject)
            {
                if (properties.CorrelationId != m_currentCorrelationId)
                {
                    // Unexpected correlation ID
                    return;
                }
            }

            m_respQueue.Add(body);
        }
Пример #12
0
        public static void log(String message)
        {
            if (message != null)
            {
                StackFrame frame  = new StackTrace().GetFrame(1);
                String     type   = frame.GetMethod().DeclaringType.ToString();
                String     method = frame.GetMethod().Name.ToString();
                String     time   = DateTime.Now.ToString(Constant.LOG_TIME_FORMAT);

                String msg = String.Format("{0}: ({1}.{2}) - {3}", time, type, method, message);

                messageQueue.Add(msg);
            }
        }
Пример #13
0
        public override void GivebackEntity(ICommunicationEntity entity)
        {
            if (_entitiesPool.Count > MaxCount)
            {
                return;
            }
            var mqEntity = entity as MqComunicationEntity;

            if (mqEntity == null)
            {
                return;
            }
            _entitiesPool.Add(mqEntity);
        }
Пример #14
0
        private void StartWorkers(List <GlobalConfig.SignatureSource> repos, int workerCount, CancellationToken cancelToken)
        {
            _repos = new System.Collections.Concurrent.BlockingCollection <GlobalConfig.SignatureSource>();
            repos.ForEach(x => _repos.Add(x));
            _repos.CompleteAdding();
            Running            = true;
            _token             = cancelToken;
            InitialTaskCount   = repos.Count;
            CompletedTaskCount = 0;

            _activeWorkers = workerCount;
            for (var i = 0; i < workerCount; i++)
            {
                Task.Factory.StartNew(StartWork);
            }
        }
Пример #15
0
        private void ThreadProcessCommands()
        {
            CommandQueue = new System.Collections.Concurrent.BlockingCollection <CCommandStucture>();

            CCommandStucture comStruct = new CCommandStucture();

            comStruct.CommandName = "Dummy";   //to remove first iteration delay
            CommandQueue.Add(comStruct);

            foreach (CCommandStucture cs in CommandQueue.GetConsumingEnumerable())
            {
                if (bEnableCommandQueue)
                {
                    Log("Process command struct");
                    ProcessCommandStructure(cs);
                }
            }
        }
Пример #16
0
        private List <Customer> BuildCustomerList(List <CommerceEntity> organizations)
        {
            var customers = new System.Collections.Concurrent.BlockingCollection <Customer>();
            Dictionary <string, Dsr>    dsrDict  = RetrieveDsrDictionary();
            Dictionary <string, string> termDict = RetrieveTermsCodeDict();

            System.Threading.Tasks.Parallel.ForEach(organizations, e => {
                Organization org = new KeithLink.Svc.Core.Models.Generated.Organization(e);

                if (org.OrganizationType == ORGANIZATION_TYPE_CUSTOMER)
                {
                    Customer myCustomer = org.ToCustomer();

                    string termKey = GetTermKey(org.BranchNumber, org.TermCode);

                    if (termDict.ContainsKey(termKey))
                    {
                        myCustomer.TermDescription = termDict[termKey];
                    }

                    string dsrKey = GetDsrKey(myCustomer.CustomerBranch, myCustomer.DsrNumber);
                    Dsr myDsr     = null;

                    if (dsrDict.ContainsKey(dsrKey))
                    {
                        myDsr = dsrDict[dsrKey];
                    }
                    else
                    {
                        dsrKey = GetDsrKey(myCustomer.CustomerBranch, DEFAULT_DSR_NUMBER);
                        if (dsrDict.ContainsKey(dsrKey))
                        {
                            myDsr = dsrDict[dsrKey];
                        }
                    }

                    myCustomer.Dsr = myDsr;

                    customers.Add(myCustomer);
                }
            });

            return(customers.ToList());
        }
Пример #17
0
        /// <summary>
        /// Adds a new processing target
        /// </summary>
        /// <param name="target">The target point to add</param>
        public void Add(ProcessingTarget target)
        {
            Targets.Add(target);

            // If live, set up a subscription
            if (Live && !LiveData.ContainsKey(target.Symbol))
            {
                var sourceList = new StockDataSet <StockDataSource>(target.Symbol, DateTime.Now, Session.SourceFile);
                var data       = new StockDataSetDerived <StockDataSink, StockDataSource, StockProcessingState>(sourceList, Session.SinkFile, CreateSink, GetProcessingState);
                var sub        = DataAccessor.Subscribe(target.Symbol, LiveInterval);
                sub.Notify += (DataAccessor.Subscription s) =>
                {
                    LiveData[s.Symbol].Item1.Add(StockDataSource.CreateFromPrice((float)s.Price));
                    LiveProcessingQueue.Add(target);
                };

                LiveData[target.Symbol] = new Tuple <StockDataSetDerived <StockDataSink, StockDataSource, StockProcessingState>, DataAccessor.Subscription>(data, sub);
            }
        }
Пример #18
0
        static void ProcessFile(string input, string output)
        {
            var inputsLine     = new System.Collections.Concurrent.BlockingCollection <string>();
            var processedLines = new System.Collections.Concurrent.BlockingCollection <string>();

            // stage #1
            var readLines = Task.Factory.StartNew(() =>
            {
                try
                {
                    foreach (var line in File.ReadLines(input))
                    {
                        inputsLine.Add(line);
                    }
                }
                finally { inputsLine.CompleteAdding(); }
            });

            // stage #2
            var processLines = Task.Factory.StartNew(() =>
            {
                try
                {
                    foreach (var line in inputsLine.GetConsumingEnumerable()
                             .Select(line => Regex.Replace(line, @"\s+", ", ")))
                    {
                        processedLines.Add(line);
                    }
                }
                finally { processedLines.CompleteAdding(); }
            });

            // stage #3
            var writeLines = Task.Factory.StartNew(() =>
            {
                File.WriteAllLines(output, processedLines.GetConsumingEnumerable());
            });

            Task.WaitAll(readLines, processLines, writeLines);
        }
Пример #19
0
        static void ThreadFunction()
        {
            while (!ShouldThreadExit())
            {
                Job <object> job;
                if (!s_jobs.TryTake(out job, 200))
                {
                    continue;
                }

                try
                {
                    job.result = job.action();
                }
                catch (System.Exception ex)
                {
                    job.exception = ex;
                }

                s_processedJobs.Add(job);
            }
        }
Пример #20
0
        public List <Account> GetAccounts()
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = "u_organization_type = '1'"; // org type of account

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

            var accounts = new System.Collections.Concurrent.BlockingCollection <Account>();

            System.Threading.Tasks.Parallel.ForEach(res.CommerceEntities, e =>
            {
                KeithLink.Svc.Core.Models.Generated.Organization org = new KeithLink.Svc.Core.Models.Generated.Organization(e);
                accounts.Add(new Account()
                {
                    Id   = Guid.Parse(org.Id),
                    Name = org.Name,
                });
            });

            return(accounts.ToList());
        }
Пример #21
0
        public static void Main(string[] argv)
        {
            var genesis  = Network.BatzMain.GetGenesis();
            var queue    = new System.Collections.Concurrent.ConcurrentQueue <uint>();
            var blocking = new System.Collections.Concurrent.BlockingCollection <uint>(queue, 100);


            int cpu = 6;

            for (int i = 0; i <= cpu; i++)
            {
                Task.Factory.StartNew(() => {
                    foreach (var nonce in blocking.GetConsumingEnumerable())
                    {
                        var block          = genesis.Clone();
                        block.Header.Nonce = nonce;
                        var hash           = block.GetHash();
                        if (hash < minhash)
                        {
                            lock (sync)
                            {
                                if (hash < minhash)
                                {
                                    Console.WriteLine("Better hash found nonce : {0}, hash : {1}", nonce, hash);
                                    minhash  = hash;
                                    minnonce = nonce;
                                }
                            }
                        }
                    }
                });
            }

            for (uint nonce = 0; nonce <= uint.MaxValue; nonce++)
            {
                blocking.Add(nonce);
            }
        }
Пример #22
0
 public void StartCrawling()
 {
     var journalsISSN = new List<string>();
     using (var stream = new FileStream("data//scopus-journals.csv", FileMode.Open))
     using (var reader = new StreamReader(stream))
     {
         var regex = new Regex("\\d{8}");
         var line = string.Empty;
         while ((line = reader.ReadLine()) != null)
         {
             var match = regex.Match(line);
             if (match.Success)
             {
                 journalsISSN.Add(match.Groups[0].Value);
                 //match = match.NextMatch();
             }
         }
     }
     var startYear = 1990;
     var finishYear = 2016;
     var workersCount = 10;
     var tasks = new Task[workersCount];
     System.Collections.Concurrent.BlockingCollection<string> processedArticles = new System.Collections.Concurrent.BlockingCollection<string>();
     System.Collections.Concurrent.BlockingCollection<string> brokenArticles = new System.Collections.Concurrent.BlockingCollection<string>();
     using (ScopusDbContext dbContext = new ScopusDbContext())
     {
         foreach (var article in dbContext.Articles.AsNoTracking())
         {
             processedArticles.Add(article.ScopusID);
         }
     }
     //for (int i = 0; i < workersCount; i++)
     {
         //tasks[i] = Task.Factory.StartNew(() =>
         //{
         var counter = 0;
         var processedEntries = new System.Collections.Concurrent.BlockingCollection<Tuple<string, int>>();
         while (journalsISSN.Count > 0)
         {
             var issn = journalsISSN.First();
             journalsISSN.RemoveAt(0);
             for (int year = finishYear; year >= startYear; year--)
             {
                 var toStart = false;
                 using (ScopusDbContext dbContext = new ScopusDbContext())
                 {
                     if (!dbContext.EntriesDone.Any(e => e.Issn == issn && e.Year == year))
                         toStart = true;
                 }
                 if (toStart)
                 {
                     var startParameters = new Tuple<string, int>(issn, year);
                     tasks[counter] = Task.Factory.StartNew((parameters) =>
                     {
                         var p = (Tuple<string, int>)parameters;
                         var worker = new Worker(processedArticles, brokenArticles);
                         var result = worker.Start(p.Item2, p.Item1);
                         processedEntries.Add(p);
                         return result;
                     }, startParameters);
                     counter++;
                 }
                 if(counter == workersCount)
                 {
                     Task.WaitAll(tasks);
                     for (int i = 0; i < tasks.Length; i++)
                     {
                         var task = (Task<List<Article>>)tasks[i];
                         if(task.Result != null)
                             UploadArticles(task.Result);
                         using (ScopusDbContext dbContext = new ScopusDbContext())
                         {
                             var entry = new EntriesDone()
                             {
                                 Issn = processedEntries.ElementAt(i).Item1,
                                 Year = processedEntries.ElementAt(i).Item2
                             };
                             dbContext.EntriesDone.Add(entry);
                             dbContext.SaveChanges();
                             Console.WriteLine("---" + processedEntries.ElementAt(i).Item1 + " - " +
                                 processedEntries.ElementAt(i).Item2.ToString() + "---");
                         }
                     }
                     counter = 0;
                 }
             }
         }
         //});
     }
 }
Пример #23
0
		static void Main () {
			// create the state machine model
			var model = new StateMachine<Player>("model");

			// create the vertices within the model
			var initial = model.CreatePseudoState("initial", PseudoStateKind.Initial);
			var operational = model.CreateState("operational");
			var choice = model.CreatePseudoState("choice", PseudoStateKind.Choice);
			var flipped = model.CreateState("flipped");
			var final = model.CreateFinalState("final");

			var history = operational.CreatePseudoState("history", PseudoStateKind.DeepHistory);
			var stopped = operational.CreateState("stopped");
			var active = operational.CreateState("active").Entry(i => i.EngageHead()).Exit(i => i.DisengageHead());

			var running = active.CreateState("running").Entry(i => i.StartMotor()).Exit(i => i.StopMotor());
			var paused = active.CreateState("paused");

			// create the transitions between vertices of the model
			initial.To(operational).Effect(i => i.DisengageHead()).Effect(i => i.StopMotor());
			history.To(stopped);
			stopped.To(running).When<string>(command => command == "play");
			active.To(stopped).When<string>(command => command == "stop");
			running.To(paused).When<string>(command => command == "pause");
			running.To().When<string>(command => command == "tick").Effect((Player instance) => instance.Count++);
			paused.To(running).When<string>(command => command == "play");
			operational.To(final).When<string>(command => command == "off");
			operational.To(choice).When<string>(command => command == "rand");
			choice.To(operational).Effect(() => Console.WriteLine("- transition A back to operational"));
			choice.To(operational).Effect(() => Console.WriteLine("- transition B back to operational"));
			operational.To(flipped).When<string>(command => command == "flip");
			flipped.To(operational).When<string>(command => command == "flip");

			// validate the model for correctness
			model.Validate();

			// create a blocking collection make events from multiple sources thread-safe
			var queue = new System.Collections.Concurrent.BlockingCollection<Object>();

			// create an instance of the player - enqueue a tick message for the machine while its playing
			var player = new Player(() => queue.Add("tick"));

			// initialises the players initial state (enters the region for the first time, causing transition from the initial PseudoState)
			model.Initialise(player);

			// create a task to capture commands from the console in another thread
			System.Threading.Tasks.Task.Run(() => {
				string command = "";

				while (command.Trim().ToLower() != "exit") {
					queue.Add(command = Console.ReadLine());
				}

				queue.CompleteAdding();
			});

			// write the initial command prompt
			Console.Write("{0:0000}> ", player.Count);

			// process messages from the queue
			foreach (var message in queue.GetConsumingEnumerable()) {
				// process the message
				model.Evaluate(player, message);

				// manage the command prompt
				var left = Math.Max(Console.CursorLeft, 6);
				var top = Console.CursorTop;
				Console.SetCursorPosition(0, top);
				Console.Write("{0:0000}>", player.Count);
				Console.SetCursorPosition(left, top);
			}
		}
Пример #24
0
 public void JobStatusChanged(Job job, Job.StatusEnum status)
 {
     SoTTodo.Add(delegate { JobStatusChangedSTA(job); });
 }
Пример #25
0
 /// <summary>
 /// 添加实体到到异步处理队列
 /// </summary>
 /// <param name="entity">实体对象</param>
 public void Push(TEntity entity)
 {
     _entityQueue.Add(entity);
 }
Пример #26
0
 public void send(double[][] data)
 {
     messageQueue.Add(data);
 }
Пример #27
0
        static void Main()
        {
            // create the state machine model
            var model = new StateMachine <Player>("model");

            // create the vertices within the model
            var initial     = model.CreatePseudoState("initial", PseudoStateKind.Initial);
            var operational = model.CreateState("operational");
            var choice      = model.CreatePseudoState("choice", PseudoStateKind.Choice);
            var flipped     = model.CreateState("flipped");
            var final       = model.CreateFinalState("final");

            var history = operational.CreatePseudoState("history", PseudoStateKind.DeepHistory);
            var stopped = operational.CreateState("stopped");
            var active  = operational.CreateState("active").Entry(i => i.EngageHead()).Exit(i => i.DisengageHead());

            var running = active.CreateState("running").Entry(i => i.StartMotor()).Exit(i => i.StopMotor());
            var paused  = active.CreateState("paused");

            // create the transitions between vertices of the model
            initial.To(operational).Effect(i => i.DisengageHead()).Effect(i => i.StopMotor());
            history.To(stopped);
            stopped.To(running).When <string>(command => command == "play");
            active.To(stopped).When <string>(command => command == "stop");
            running.To(paused).When <string>(command => command == "pause");
            running.To().When <string>(command => command == "tick").Effect((Player instance) => instance.Count++);
            paused.To(running).When <string>(command => command == "play");
            operational.To(final).When <string>(command => command == "off");
            operational.To(choice).When <string>(command => command == "rand");
            choice.To(operational).Effect(() => Console.WriteLine("- transition A back to operational"));
            choice.To(operational).Effect(() => Console.WriteLine("- transition B back to operational"));
            operational.To(flipped).When <string>(command => command == "flip");
            flipped.To(operational).When <string>(command => command == "flip");

            // validate the model for correctness
            model.Validate();

            // create a blocking collection make events from multiple sources thread-safe
            var queue = new System.Collections.Concurrent.BlockingCollection <Object>();

            // create an instance of the player - enqueue a tick message for the machine while its playing
            var player = new Player(() => queue.Add("tick"));

            // initialises the players initial state (enters the region for the first time, causing transition from the initial PseudoState)
            model.Initialise(player);

            // create a task to capture commands from the console in another thread
            System.Threading.Tasks.Task.Run(() => {
                string command = "";

                while (command.Trim().ToLower() != "exit")
                {
                    queue.Add(command = Console.ReadLine());
                }

                queue.CompleteAdding();
            });

            // write the initial command prompt
            Console.Write("{0:0000}> ", player.Count);

            // process messages from the queue
            foreach (var message in queue.GetConsumingEnumerable())
            {
                // process the message
                model.Evaluate(player, message);

                // manage the command prompt
                var left = Math.Max(Console.CursorLeft, 6);
                var top  = Console.CursorTop;
                Console.SetCursorPosition(0, top);
                Console.Write("{0:0000}>", player.Count);
                Console.SetCursorPosition(left, top);
            }
        }
Пример #28
0
        protected override void CollectChunks(System.Collections.Concurrent.BlockingCollection <IReadOnlyList <IObjectResolver> > chunkedSource)
        {
            using (var file = File.OpenRead(_filePath))
                using (var stringReader = new StreamReader(file))
                    using (var xmlReader = XmlReader.Create(stringReader, new XmlReaderSettings()
                    {
                        IgnoreWhitespace = true,
                        IgnoreComments = true
                    }))
                    {
                        xmlReader.MoveToContent();

                        var chunk = new List <IObjectResolver>(1000);

                        var nameToIndexMap         = new Dictionary <string, int>();
                        var indexToObjectAccessMap = new Dictionary <int, Func <dynamic, object> >();

                        var elements = new Stack <DynamicElement>();

                        do
                        {
                            switch (xmlReader.NodeType)
                            {
                            case XmlNodeType.Element:
                                var element = new DynamicElement
                                {
                                    { "element", xmlReader.LocalName },
                                    { "parent", elements.Count > 0 ? elements.Peek() : null },
                                    { "value", xmlReader.HasValue ? xmlReader.Value : null }
                                };

                                element.Add(xmlReader.Name, element);

                                elements.Push(element);

                                if (xmlReader.HasAttributes)
                                {
                                    while (xmlReader.MoveToNextAttribute())
                                    {
                                        element.Add(xmlReader.Name, xmlReader.Value);
                                    }
                                }

                                xmlReader.MoveToElement();
                                break;

                            case XmlNodeType.Text:
                                elements.Peek().Add("text", xmlReader.Value);
                                break;

                            case XmlNodeType.EndElement:
                                chunk.Add(new DictionaryResolver(elements.Pop()));
                                break;
                            }

                            if (chunk.Count >= 1000)
                            {
                                chunkedSource.Add(chunk);
                                chunk = new List <IObjectResolver>(1000);
                            }
                        }while (xmlReader.Read());

                        if (chunk.Count > 0)
                        {
                            chunkedSource.Add(chunk);
                        }
                    }
        }
Пример #29
0
        private async void UpdateHomeItems()
        {
            #region Subscriptions

            Log.Info("Updating the videos on the home page");

            PlaylistDataType YTItemsListTemp = new PlaylistDataType()
            {
                Title = "Today"
            };
            PlaylistDataType YTItemsListTempYesterday = new PlaylistDataType()
            {
                Title = "Yesterday"
            };
            PlaylistDataType YTItemsListTempTwoDays = new PlaylistDataType()
            {
                Title = "Two Days Ago"
            };
            PlaylistDataType YTItemsListTempThreeDays = new PlaylistDataType()
            {
                Title = "Three Days Ago"
            };
            PlaylistDataType YTItemsListTempFourDays = new PlaylistDataType()
            {
                Title = "Four Days Ago"
            };
            PlaylistDataType YTItemsListTempFiveDays = new PlaylistDataType()
            {
                Title = "Five Days Ago"
            };

            System.Collections.Concurrent.BlockingCollection <Google.Apis.YouTube.v3.Data.SearchResult> searchResponseList = new System.Collections.Concurrent.BlockingCollection <Google.Apis.YouTube.v3.Data.SearchResult>();

            var service = await YoutubeMethodsStatic.GetServiceAsync();

            await Task.Run(() =>
            {
                Parallel.ForEach(Constants.MainPageRef.subscriptionsList, subscription =>
                {
                    try
                    {
                        var tempService        = service.Search.List("snippet");
                        tempService.ChannelId  = subscription.Id;
                        tempService.Order      = SearchResource.ListRequest.OrderEnum.Date;
                        tempService.MaxResults = 8;
                        var response           = tempService.Execute();
                        foreach (var video in response.Items)
                        {
                            searchResponseList.Add(video);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("A subscription's videos failed to load.");
                        subscription.Thumbnail = null;
                        Log.Error(JsonConvert.SerializeObject(subscription));
                        Log.Error(ex.Message);
                    }
                });
            });

            var orderedSearchResponseList = searchResponseList.OrderByDescending(x => x.Snippet.PublishedAt).ToList();

            Log.Info("Ordering videos by date and placing them in the correct list");
            foreach (var video in orderedSearchResponseList)
            {
                var methods = new YoutubeMethods();
                if (video != null && video.Id.Kind == "youtube#video" && video.Id.VideoId != null && video.Snippet.LiveBroadcastContent != "live")
                {
                    try
                    {
                        DateTime now       = DateTime.Now;
                        var      ytubeItem = methods.VideoToYoutubeItem(video);
                        if (ytubeItem.Failed != true)
                        {
                            if (video.Snippet.PublishedAt > now.AddHours(-24))
                            {
                                YTItemsListTemp.Items.Add(ytubeItem);
                            }
                            else if (video.Snippet.PublishedAt > now.AddHours(-48))
                            {
                                YTItemsListTempYesterday.Items.Add(ytubeItem);
                            }
                            else if (video.Snippet.PublishedAt > now.AddHours(-72))
                            {
                                YTItemsListTempTwoDays.Items.Add(ytubeItem);
                            }
                            else if (video.Snippet.PublishedAt > now.AddHours(-96))
                            {
                                YTItemsListTempThreeDays.Items.Add(ytubeItem);
                            }
                            else if (video.Snippet.PublishedAt > now.AddHours(-120))
                            {
                                YTItemsListTempFourDays.Items.Add(ytubeItem);
                            }
                            else if (video.Snippet.PublishedAt > now.AddHours(-144) && video.Snippet.PublishedAt <= now)
                            {
                                YTItemsListTempFiveDays.Items.Add(ytubeItem);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(String.Format("A video failed to load into the home page. Json: {0}", JsonConvert.SerializeObject(video)));
                        Log.Error(ex.Message);
                    }
                }
            }

            YTItems.Add(YTItemsListTemp);
            YTItems.Add(YTItemsListTempYesterday);
            YTItems.Add(YTItemsListTempTwoDays);
            YTItems.Add(YTItemsListTempThreeDays);
            YTItems.Add(YTItemsListTempFourDays);
            YTItems.Add(YTItemsListTempFiveDays);
            #endregion

            LoadingRing.IsActive = false;

            Parallel.ForEach(YTItems, playlist =>
            {
                var methodsLocal = new YoutubeMethods();
                methodsLocal.FillInViews(playlist.Items, service);
            });
        }