I am currently implementing a task that takes a lot of time. Basically, what I want to do is to run multiple tasks inside foreach loop. I tried using Parallel.ForEach its freezing my UI. I wanna be able to call like 10 uids at a time.
foreach (var uid in listBox2.Items)
{
if (StopEmail) break;
Application.DoEvents();
string jsonstring = GetEmails(uid.ToString(), token);
if (jsonstring != null)
{
label6.Text = " Current UID: " + listBox2.Items.IndexOf(uid);
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonstring);
string idstt = jsonResponse["email"];
if (idstt != null)
{
listBox3.Items.Add(idstt);
label4.Text = "Total Emails: " + listBox3.Items.Count.ToString();
}
}
}
Here is my Parallel.ForEach Code:
var files = listBox2.Items.Cast<String>().ToList();
Parallel.ForEach(files, uid =>
{
Application.DoEvents();
string jsonstring = GetEmails(uid.ToString(), token);
if (jsonstring != null)
{
this.Invoke(new MethodInvoker(delegate()
{
label6.Text = " Current UID: " + listBox2.Items.IndexOf(uid);
}));
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonstring);
string idstt = jsonResponse["email"];
if (idstt != null)
{
this.Invoke(new MethodInvoker(delegate()
{
listBox3.Items.Add(idstt);
label4.Text = "Total Emails: " + listBox3.Items.Count.ToString();
}));
}
}
});