Limit the number of parallel threads in C#

前端 未结 5 1777
我寻月下人不归
我寻月下人不归 2020-11-28 14:58

I am writing a C# program to generate and upload a half million files via FTP. I want to process 4 files in parallel since the machine have 4 cores and the file generating t

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 15:40

    Task Parallel Library is your friend here. See this link which describes what's available to you. Basically framework 4 comes with it which optimises these essentially background thread pooled threads to the number of processors on the running machine.

    Perhaps something along the lines of:

    ParallelOptions options = new ParallelOptions();
    
    options.MaxDegreeOfParallelism = 4;
    

    Then in your loop something like:

    Parallel.Invoke(options,
     () => new WebClient().Upload("http://www.linqpad.net", "lp.html"),
     () => new WebClient().Upload("http://www.jaoo.dk", "jaoo.html"));
    

提交回复
热议问题