我正面临着相当大的困难,我想使用Parallel.Foreach
迭代列表。
所以想象一下这个
static List<string> proxyList = new List<string>();
static List<string> websiteList = new List<string>();
每个列表看起来都像这样
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
网站列表
https://google.com
https://spotify.com
https://duckduckgo.com
https://amazon.com
我想要达到这样的目标,但我不知道如何,无论我如何转弯,我似乎无法找到任何逻辑。
Foreach(var proxy in proxyList)
{
If(proxyIsAlive)
//Try to connect to the first website in the website list
else
//Try the next proxy until I get a working one
//and then try to connect to the most recent one
}
}
我面临的问题是我必须知道如何访问网站列表中的网站,我想连接到
编辑:这就是我的逻辑到目前为止的样子
private static void Connect()
{
string tproxy = "";
int port;
foreach (var website in websiteList)
{
foreach (var proxy in proxyList)
{
var proxySplit = proxy.Split(':');
tproxy = proxySplit[0];
port = Convert.ToInt32(proxySplit[1]);
//if(ProxyIsAlive)
}
//Use that proxy down here to connect
}
}
我只想退出代理foreach IF ProxyIsAlive返回true
答案 0 :(得分:2)
注意:
注意:Parallel.ForEach适用于CPU绑定任务,您需要这样做 小心你不仅浪费资源阻止线程等待 IO操作完成
持有代理信息的类
public class Proxy
{
public string Host { get; set; }
public int Port { get; set; }
public DateTime LastSuccess { get; set; }
public Proxy(string value)
{
var proxySplit = value.Split(':');
Host = proxySplit[0];
Port = Convert.ToInt32(proxySplit[1]);
LastSuccess = DateTime.MinValue;
}
}
并行运行的代码
var proxies = proxyList.Select(x => new Proxy(x)).ToList();
Parallel.ForEach(webSites, new ParallelOptions { MaxDegreeOfParallelism = 4 }, site =>
{
Parallel.ForEach(proxies.OrderByDescending(x => x.LastSuccess), new ParallelOptions { MaxDegreeOfParallelism = 4 }, proxy =>
{
if(!CheckProxy(proxy))
{
//check next proxy
return;
}
// if we found a good proxy
// update the lastSuccess so we check that first
proxy.LastSuccess = DateTime.Now;
// do something to the website
});
});
}
注意:如果你有CPU绑定代码,这可能不是最好的方法, 并行性是合适的;如果你有I / O绑定的代码,异步就是 适当。在这种情况下,HttpClientExtension.GetHttpResponse是 显然I / O,所以理想的消费代码将是异步的。
我会考虑查找主题 IO绑定操作的并行执行
现有的SO问题涉及此问题
答案 1 :(得分:0)
所以这就是我最终做的事情。
private static void ConnectToWebsite()
{
var proxyIP = "";
int port;
foreach (var website in WebsiteList)
{
foreach (var proxy in proxyList)
{
var proxySplit = proxy.Split(':');
proxyIP = proxySplit[0];
var convert = Int32.TryParse(proxySplit[1], out port);
if(HttpClientExtension.GetHttpResponse(getCMYIP, proxyIP, port))
Console.WriteLine(website + proxy);
}
}
}
这将检查代理,直到它找到一个有效的代理。 现在我需要让这个异步加速。