List<List<KeyValuePair<long, string>>> batchList = new List<List<KeyValuePair<long, string>>>(10);
//Get Credentials and timeout value one time
ICredentials credentials = GetCredentials(); //Get default credentials, doesnt change
int clickTimeout = 3; //will be seconds
int j = 1;
//Loop
foreach (List<KeyValuePair<long, string>> batch in batchList)
{
LogHelper.InsertJobLog("ServiceName", string.Format("Executing batch: {0}.", (j).ToString()), reference);
HandleProcessBatch(batch, credentials, clickTimeout);
LogHelper.InsertJobLog("ServiceName", string.Format("End Executing batch: {0}.", (j).ToString()), reference);
j++;
}
// ....
//Handle batches of processes
private static void HandleProcessBatch(List<KeyValuePair<long, string>> procList, ICredentials credentials, int clickTimeout)
{
try
{
//Task list
List<Task> listaTarefas = new List<Task>();
foreach (KeyValuePair<long, string> proc in procList)
{
LogHelper.InsertJobLog("ServiceName", string.Format("ProcID {0} will be added to the execution list: {1}", proc.Key, proc.Value), null);
listaTarefas.Add(
Task.Factory.StartNew(
() => SimulateURLRequest(proc.Key,proc.Value, credentials, clickTimeout)
)
);
}
//Wait for all tasks in this list to end
Task.WaitAll(listaTarefas.ToArray());
}
catch (Exception ex)
{
EventLogWrite.Error("ServiceName-HandleProcessBatch", ex.Message);
}
}
//Called in diferrent threads
private static void SimulateURLRequest(long processID, string processURL, ICredentials credentials, int timeout)
{
try
{
Uri ipacURL;
if (!Uri.TryCreate(processURL, UriKind.Absolute, out ipacURL) || (ipacURL.Scheme != Uri.UriSchemeHttp && ipacURL.Scheme != Uri.UriSchemeHttps))
{
LogHelper.InsertJobLog("ServiceName", string.Format("Proc {0} URL not valid: {1}", processID.ToString(), processURL),null);
return;
}
WebRequest wr = WebRequest.Create(ipacURL);
wr.Credentials = credentials;
wr.Timeout = (timeout * 1000);
HttpWebResponse answer = (HttpWebResponse)wr.GetResponse();
LogHelper.InsertJobLog("ServiceName", string.Format("Proc {0} result: {1}", processID.ToString(), Enum.GetName(typeof(HttpStatusCode), answer.StatusCode)),null);
}
catch (WebException wex)
{
LogHelper.InsertJobLog("ServiceName", wex.Message,null);
}
catch (Exception ex)
{
LogHelper.InsertJobLog("ServiceName", ex.Message, null);
EventLogWrite.Error("ServiceName-SimulateURLRequest", ex.Message);
}
}