C# Parallel.ForEach MaxDegreeOfParallelism并行选项不工作?
我是不是遗漏了什么?我尝试在“MaxDegreeOfParallelism=”选项中输入一个设置值,如1或4,但在下面的示例中,它是由和上/下选择器指定的 我的MaxDegreeOfParallelism并行选项不起作用有什么原因吗? 现在程序似乎使用了它想要的任意多的线程。我也有一个内存泄漏的大时间,我假设这是由于Parallel.ForEach循环,因为泄漏之前不存在C# Parallel.ForEach MaxDegreeOfParallelism并行选项不工作?,c#,multithreading,parallel.foreach,C#,Multithreading,Parallel.foreach,我是不是遗漏了什么?我尝试在“MaxDegreeOfParallelism=”选项中输入一个设置值,如1或4,但在下面的示例中,它是由和上/下选择器指定的 我的MaxDegreeOfParallelism并行选项不起作用有什么原因吗? 现在程序似乎使用了它想要的任意多的线程。我也有一个内存泄漏的大时间,我假设这是由于Parallel.ForEach循环,因为泄漏之前不存在 private void NumericUpDown1_ValueChanged(object sender, EventA
private void NumericUpDown1_ValueChanged(object sender, EventArgs e)
{
threadCount = threadCountUD.Value;
threadC = Decimal.ToInt32(threadCount);
}
private void MainWork()
{
var maxThread = new ParallelOptions
{
MaxDegreeOfParallelism = threadC,
};
var cookies = new CookieContainer();
proxies = File.ReadAllLines(proxPath);
fileInfo = File.ReadAllLines(path);
var proxAndNames = proxies.Zip(fileInfo, (n, w) => new { Proxies = n, Name = w });
bool repeat = true;
Parallel.ForEach(proxAndNames.AsParallel().ToArray(),maxThread, async (var) =>
{ while (repeat)
{
if (stopBtn is true)
{
break;
}
var httpClientHandler = new HttpClientHandler
{
Proxy = new WebProxy(var.Proxies),
AllowAutoRedirect = true,
CookieContainer = cookies,
UseCookies = false,
UseDefaultCredentials = false,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
UseProxy = true
};
using (var client = new HttpClient(httpClientHandler, false))
{
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0");
client.BaseAddress = new Uri("https://www.google.com/");
var cts = new CancellationTokenSource();
try
{
HttpResponseMessage response = await client.GetAsync(var.Name.AsParallel() + "/");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string grabbed = await client.GetStringAsync(var.Name.AsParallel() + "/");
}
}
catch (TaskCanceledException)
{
if (!cts.Token.IsCancellationRequested)
{
}
else
{
// Cancelled for some other reason
}
}
catch (HttpRequestException ex)
{
proxBox.Invoke(new Action(() => proxBox.Text += ex.Message + System.Environment.NewLine));
}
finally
{
client.Dispose();
cts.Dispose();
}
}
}
});
}
请查看关于张贴代码的指导。特别是“/get requests going on here”似乎是您将任务(
async
/Wait
)与并行混合的最有趣的地方。ForEach
…@AlexeiLevenkov感谢您的回复。我现在将编辑并修复这个问题:)很明显,您的代码占用了大量内存。`Parallel`一次又一次地完成自己的任务。制作任务
在内存中的成本非常高,您无法将并行.ForEach
与异步方法一起使用。使用Task.whalll
。请看其中一个问答:。由于您实际上是在启动一些射击和遗忘动作,MaxDegreeOfParallelism
不会执行您期望的操作,因为主体动作
立即完成。不能也不会等待它。将并行类用于I/O绑定的工作负载是非常有问题的。还要看一看:HttpClient
旨在实例化一次,并在应用程序的整个生命周期中重复使用。为每个请求实例化一个HttpClient
类将耗尽重载下可用的套接字数量。