Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Parameterized Threads Efficiency

Would there a more elegant way of writing the following syntax?

        Thread t0 = new Thread(new ParameterizedThreadStart(doWork));
        t0.Start('someVal');
        t0.Join();

        Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
        t1.Start('someDiffVal');
        t1.Join();

Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?

If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:

        Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
        t1.Start('someVal');
        t1.Start('someDiffVal');
like image 252
nightdev Avatar asked Jan 21 '26 21:01

nightdev


1 Answers

Why would you start a thread and then join against it immediately?

I'd normally do something like this:

List<Thread> threads = new List<Thread>();

foreach (string item in items)
{
    string copy = item; // Important due to variable capture
    ThreadStart ts = () => DoWork(copy); // Strongly typed :)
    Thread t = new Thread(ts);
    t.Start();
    threads.Add(t);
}

foreach (Thread t in threads)
{
    t.Join();
}
like image 162
Jon Skeet Avatar answered Jan 24 '26 12:01

Jon Skeet