public class Scraper
{
private SemaphoreSlim semaphoreSlim = 7;
public void Scraper(int concurrentThreads)
{
semaphoreSlim = new SemaphoreSlim(concurrentThreads);
ServicePointManager.FindServicePoint(new Uri(baseUrl)).ConnectionLimit = concurrentThreads;
}
public async Task<List<ApiGetStringOutcome>> GetStringsFromUrlList(List<string> apiUrls)
{
List<Task<ApiGetStringOutcome>> tasks = new List<Task<ApiGetStringOutcome>>();
foreach (string apiUrl in apiUrls)
{
tasks.Add(GetStringDataAsync(apiUrl));
}
await Task.WhenAll(tasks);
return new List<ApiGetStringOutcome>(tasks.Select(t => t.Result));
}
private async Task<ApiGetStringOutcome> GetStringDataAsync(string apiUrl, ApiGameSearchParameters gameSearchParameters = null)
{
await semaphoreSlim.WaitAsync(); // Wait until semaphore is available
try
{
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);
}
catch (Exception ex)
{
// Stuff here
}
finally
{
semaphoreSlim.Release();
}
}
}
public class MainApp
{
public void Start()
{
// blah...
getStringOutcomes = await Task.Run(() => apiDataService.GetStringsFromUrlList(urlList));
}
}
public class Scraper
{
private SemaphoreSlim semaphoreSlim = 7;
public void Scraper(int concurrentThreads)
{
semaphoreSlim = new SemaphoreSlim(concurrentThreads);
ServicePointManager.FindServicePoint(new Uri(baseUrl)).ConnectionLimit = concurrentThreads;
}
public async Task<List<ApiGetStringOutcome>> GetStringsFromUrlList(List<string> apiUrls)
{
List<Task<ApiGetStringOutcome>> tasks = new List<Task<ApiGetStringOutcome>>();
foreach (string apiUrl in apiUrls)
{
tasks.Add(GetStringDataAsync(apiUrl));
}
await Task.WhenAll(tasks);
return new List<ApiGetStringOutcome>(tasks.Select(t => t.Result));
}
private async Task<ApiGetStringOutcome> GetStringDataAsync(string apiUrl, ApiGameSearchParameters gameSearchParameters = null)
{
await semaphoreSlim.WaitAsync(); // Wait until semaphore is available
try
{
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);
}
catch (Exception ex)
{
// Stuff here
}
finally
{
semaphoreSlim.Release();
}
}
}
public class MainApp
{
public void Start()
{
// blah...
getStringOutcomes = await Task.Run(() => apiDataService.GetStringsFromUrlList(urlList));
}
}