在另一个任务中启动任务正在复制我的 WebRequests

Starting tasks inside another task is duplicating my WebRequests

我使用下面的代码在线检查一些 pdf 文件并 return 相应的字符串。

问题是:当我添加第二个 Task.Factory.StartNew() 时,它开始复制所有请求,但仍然 return 只有一个答案(应该是)。

我需要它尽可能快,这样我就不会浪费时间向服务器发送两个请求。

public static void Main(string[] args)
        {

            var listT = new List<string>()
            {
                "24006025062"
            };

            var task = listT.Select(x => Task.Factory.StartNew(() => TesteTask(x)));

            Task.WaitAll(task.ToArray(), TimeSpan.FromSeconds(120));

            List<string> results = new List<string>();
            foreach (var result in task)
            {
                results.Add(result.Result);
            }
        }

private static string TesteTask(string codCart)
    {
        var teste = new Consulta();
        var retorno = string.Empty;

        var session = teste.GetCaptcha();


        for (int i = 0; i < 10; i++)
        {
            session.CaptchaResolvida = QuebraCaptcha(session.CaptchaCodificada).CaptchaResolvida;
            if (session.CaptchaResolvida.Length > 0)
            {
                var links = teste.Consulta(codCart, session).Retorno;

                if (links.Any())
                {
                    var tasks = links.Select(x => Task.Factory.StartNew(() => Executa(teste, session, x)));

                    Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(120));

                    var modelList = from Result in tasks select Result.Result;

                    retorno = teste.FinalizaProcesso(modelList.ToList());

                    break;
                }
            }


        }

        return retorno;
    }

private static string Executa(Consulta teste, Model<Request> session, string link)
    {
        var retorno = string.Empty;

        for (int i = 0; i < 10; i++)
        {
            var CaptchaResolvida = QuebraCaptcha(teste.GetCaptchaPdf(session)).CaptchaResolvida;

            if (CaptchaResolvida != null && CaptchaResolvida != string.Empty)
            {
                var status = teste.BaixaPdf(link, CaptchaResolvida, session);

                if (status != string.Empty)
                {
                    retorno = status;
                    break;
                }
            }
        }

        return retorno;
    }

Ps:这是我第一次post关于堆栈溢出,如果我不够清楚请告诉我!

您出现此行为是因为您对 Select 返回的 IEnumerable 进行了两次迭代。试试这个:

public static void Main(string[] args)
    {

        var listT = new List<string>()
        {
            "24006025062"
        };

        var task = list
            .Select(x => Task.Factory.StartNew(() => TesteTask(x)))
            .ToArray();

        Task.WaitAll(task, TimeSpan.FromSeconds(120));

        List<string> results = new List<string>();
        foreach (var result in task)
        {
            results.Add(result.Result);
        }
    }

通过将 ToArray() 移动到 Select() 之后,它只创建一次结果 IEnumerable 而不是两次。

希望对您有所帮助!