簡體   English   中英

我如何才能等到十個任務完成,然后再執行下十個任務

[英]How can I wait till ten tasks are completed then execute the next ten tasks

我正在訪問一個Web服務,該服務的請求數有限,您可以每分鍾發送一次。 我必須訪問X> 10個條目,但是每分鍾只能創建10個條目。

我將服務理解為Singleton,可以從代碼的不同部分進行訪問。 現在,我需要一種方法來知道發出了多少個請求以及是否允許我提出一個新請求。

因此,我做了一些示例代碼,其中添加了100個任務。 每個任務都有3秒的延遲和Task時,再也沒有出現過前十分任務通過才能執行Task.WhenAny 但是,當我從列表中刪除已完成的任務時, An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code ”異常。

我怎樣才能解決這個問題?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Test
    {
        private static Test instance;
        public static Test Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Test();
                }
                return instance;
            }
        }


        private List<Task> taskPool = new List<Task>();
        private Test()
        {

        }

        public async void AddTask(int count)
        {
            // wait till less then then tasks are in the list
            while (taskPool.Count >= 10)
            {
                var completedTask = await Task.WhenAny(taskPool);
                taskPool.Remove(completedTask);
            }

            Console.WriteLine("{0}, {1}", count, DateTime.Now);

            taskPool.Add(Task.Delay(TimeSpan.FromSeconds(3)));
        }
    }
}

一個好老的Sempahore解決了我的問題。 這是一個經典的線程問題,有一些經過測試的概念如何解決它,而這正是我正在使用的概念:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Test
    {
        private static Test instance;
        public static Test Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Test();
                }
                return instance;
            }
        }

        private static Semaphore _pool = new Semaphore(0, 10);
        private Test()
        {
            _pool.Release(10);
        }

        public async void AddTask(int count)
        {   
            _pool.WaitOne();
            var task = Task.Delay(TimeSpan.FromSeconds(3));
            Console.WriteLine("{0}, {1}", count, DateTime.Now);
            await task;
            _pool.Release();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM