我正面临着相当大的困难,我想使用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
备注:
注意: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问题涉及到这样的问题
所以这就是我最终做的事情。
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);
}
}
}
这将检查代理,直到它找到一个工作。现在我需要使这个异步加速。