Start multiple threads at the same time without any two attempts or failures

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++;
          //My Codes
    }
    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.

+4
2

.

, . page , , . , , ( , , , ).

page, , , , :

for (int page = 1; page <= 10; page++)
{
    int pageCopy = page;
    Thread thread = new Thread(unused => my_method(pageCopy , count));
    thread.Name = "Thread - " + pageCopy.ToString();
    thread.Start();
}

, , ; - , , while, . Thread, , List<Thread>, , , , Join , .

+5

. -, Interlocked.Exchange. -, .

private volatile int count = 0;
private HashSet<int> hs_pages = new HashSet<int>();
private syncRoot = new object();

for (int page = 1; page <= 10; page++)
{
    Thread thread = new Thread(page => my_method(page));
    thread.Name = "Thread - " + page.ToString();
    thread.Start(page);
}

while(count< 10)
{

}

my_method

public void my_method(object obj)
{
    page = obj as int;

    if (hs_pages.Add(page))
    {
        lock (syncRoot) { count++; }
        //My Codes
    }
    else
    {
        MessageBox.Show("this is duplicate of page : " + page.ToString());
    }
}
-1

All Articles