예제 #1
0
        static async Task DoThrottledSampleWork(int concurrencyLevel)
        {
            var       engine            = new ThrottledService();
            const int CONCURRENCY_LEVEL = 5;
            int       nextIndex         = 0;
            var       throttledTasks    = new List <Task <string> >();

            while (nextIndex < CONCURRENCY_LEVEL && nextIndex < 20)
            {
                throttledTasks.Add(engine.ProducePithySaying());
                nextIndex++;
            }
            while (throttledTasks.Count > 0)
            {
                try {
                    Task <string> finishedTask = await Task.WhenAny(throttledTasks);

                    throttledTasks.Remove(finishedTask);
                    Console.WriteLine(await finishedTask);
                } catch (Exception exc) {
                    Console.WriteLine(exc.ToString());
                }
                if (nextIndex < 20)
                {
                    throttledTasks.Add(engine.ProducePithySaying());
                    nextIndex++;
                }
            }
        }
예제 #2
0
        static async Task DoSampleWork()
        {
            var engine   = new ThrottledService();
            var allTasks = new List <Task <string> >();

            for (int i = 0; i < 20; i++)
            {
                allTasks.Add(engine.ProducePithySaying());
                await Task.Delay(250);
            }
            foreach (var task in allTasks)
            {
                try {
                    Console.WriteLine(await task);
                } catch (InvalidOperationException) {
                    Console.WriteLine("This task failed");
                }
            }
        }