Parallel.Foreach在完成线程之前先关闭线程

时间:2019-02-13 13:15:09

标签: c#

我有一个C#控制台应用程序,它通过Internet发送请求并获取响应,我正在使用parallel.Foreach。

当我使用发送的小请求时,它工作正常,但是如果我发送了很多请求,则没有任何结果,在跟踪问题之后,我发现线程在完成之前退出并打印结果:

public static void Main(string[] args)
    {

        int threads = Convert.ToInt32(File.ReadAllText(@"threads.txt"));

        var workItems = new List<object>();


        foreach (string user in File.ReadLines("x.txt"))
        {


            foreach (string pass in File.ReadLines("y.txt"))
            {


                foreach (string line in File.ReadLines("z.txt"))
                {

                    workItems.Add(new object[] { line, user, pass });


                }
                ///////////////////////////////////////////////////////////////////
            }
        }
        var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads };
        var results = Parallel.ForEach(workItems, opts, tesTConn );

        Console.WriteLine("Press ENTER to exit.");
        Console.Read();


    }

    //string domain, int port, string username, string password

    public static void tesTConn(object state)
    {

    }

1 个答案:

答案 0 :(得分:0)

这对我来说很好。 (请注意,我正在使用.net 4.7.1的anon touple类型)

class Program
{
    static void Main(string[] args)
    {
        var work = new List<(string, string, string)> { ("a", "a", "a"), ("a", "a", "b"), ("a", "a", "c"), ("a", "a", "d"), ("a", "a", "e"), ("a", "a", "f"), ("a", "a", "g") };
        var threads = 3;
        var opts = new ParallelOptions { MaxDegreeOfParallelism = threads };
        Parallel.ForEach(work, opts, Test);


        Console.WriteLine("Done!");
        Console.ReadKey();
    }

    static void Test((string, string, string) item)
    {
        //Do work....
        Thread.Sleep(100);
        Console.WriteLine($"{item.Item1}:{item.Item2}:{item.Item3}");
    }
}

输出:

a:a:c
a:a:e
a:a:a
a:a:d
a:a:f
a:a:b
a:a:g
Done!