How can I start some threads at the same time without “starting twice” or “crashing” one of them? I will explain my question with an example:
private int count = 0;
private HashSet<int> hs_pages = new HashSet<int>();
for (int page = 1; page <= 10; page++)
{
Thread thread = new Thread(unused => my_method(page));
thread.Name = "Thread - " + page.ToString();
thread.Start();
}
while(count < 10)
{
}
and my_method()implemented as:
public void my_method(int page)
{
if (hs_pages.Add(page))
{
count++;
}
else
{
MessageBox.Show("this is duplicate of page : " + page.ToString());
}
}
after running this code, I found out that some pages (1-10) do not start, and some pages start twice.
therefore while()never ends due to these duplicates and fails.
How can I fix these duplicates and crashes?
My fail value is not an “error”, I mean, for example, it my_method(4)never starts, and my sense of duplication is, for example, my_method(3)being executed twice.
, , Parallel.ForEach, , Thread.