Ejemplo n.º 1
0
        public static long AsyncCalcOccurences(string word, string langCode)
        {
            if (queriesQueue == null)
            {
                // Create the queries queue and start the working threads
                queriesQueue   = new Queue <WordAndLang>();
                workingThreads = new Thread[MAX_THREADS_COUNT];
                for (int i = 0; i < MAX_THREADS_COUNT; i++)
                {
                    workingThreads[i]      = new Thread(new ThreadStart(ProcessQueriesQueue));
                    workingThreads[i].Name = "Google.Query.Thread#" + i;
                    workingThreads[i].Start();
                }
            }

            if (word.Contains(" "))
            {
                word = "\"" + word + "\"";
            }

            // Check the cache first
            string query = word + " lang:" + langCode;

            if (GoogleOccurencesCache.IsInCache(query))
            {
                long occurences = GoogleOccurencesCache.GetFromCache(query);
                return(occurences);
            }

            // Add the query to a queue for asynchronous processing
            lock (queriesQueue)
            {
                WordAndLang wordAndLang = new WordAndLang(word, langCode);
                queriesQueue.Enqueue(wordAndLang);
                Monitor.Pulse(queriesQueue);
            }

            return(0);
        }
Ejemplo n.º 2
0
 private static void ProcessQueriesQueue()
 {
     while (true)
     {
         WordAndLang query = null;
         lock (queriesQueue)
         {
             if (queriesQueue.Count > 0)
             {
                 query = queriesQueue.Dequeue();
             }
             else
             {
                 Monitor.Wait(queriesQueue);
             }
         }
         if (query != null)
         {
             Console.WriteLine("Thread {0} - job {1} of {2}",
                               Thread.CurrentThread.Name, queriesQueue.Count, queriesQueue.Count);
             GetOccurences(query.Word, query.Lang);
         }
     }
 }