I believe you can share CookieContainer
instances between WebClient
objects. So once you've authenticated, re-use the same CookieContainer
for each new client you create. Just take care that your subsequent requests are not modifying the CookieContainer
, otherwise you may have a race condition because I doubt the class is thread-safe for parallel modifications.
First, modify CookieAwareWebClient
with a custom constructor that can have a cookie container passed in. Also, provide a way to get the container reference via a property:
class CookieAwareWebClient : WebClient
{
private CookieContainer cookie;
public CookieContainer Cookie { get { return cookie; } }
public CookieAwareWebClient() {
cookie = new CookieContainer();
}
public CookieAwareWebClient(CookieContainer givenContainer) {
cookie = givenContainer;
}
}
Then your Scrapper
class should pass in its own CookieContainer
to each client after authentication:
public string DowloadSomeData(int pages)
{
string someInformation = string.Empty;
CookieContainer cookie = this._web.Cookie;
Parallel.For(0, pages, i =>
{
// pass in the auth'ed cookie
var web = new CookieAwareWebClient(cookie);
html = web.DownloadString("http://example.com/");
someInformation += this.GetSomeInformation(html)
});
return someInformation;
}