Alex James
Alex James

Reputation: 371

How to run C# threads in sequence

I have a situation in which I want to start 3 threads called: tr1, tr2 and tr3

I want tr2 to start after tr1 and tr3 to start after tr2.

How can I achieve this?

Upvotes: 2

Views: 3032

Answers (6)

Henk Holterman
Henk Holterman

Reputation: 273179

In Fx4 you can use Tasks and the ContinueWith feature.

And while it does make sense to have Tasks (Jobs) that must be run in sequence, it does not seem so sensible for Threads. Why don't you use 1 Thread that executes m1(), m2() and m3() in sequence? Especially if you are on Fx <= 3.5

Another aspect here is error handling. The tasks library will handle that more or less invisible, but without it you need to take care.

Upvotes: 1

Jan Bodnar
Jan Bodnar

Reputation: 11637

The reason why you would want to run threads in sequence is simple: you want to compare it with the parallel one and see the speed improvements.

The following example runs threads in sequence and computes the elapsed time. Comment the Join method in the first loop and uncomment the second loop to have the threads run concurrently.

using System.Diagnostics;

Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

var sw = new Stopwatch();
sw.Start();

Thread[] threads = new Thread[10];

for (var i = 0; i < 10; i++)
{
    var t = new Thread(() =>
    {
        var id = Thread.CurrentThread.ManagedThreadId;
        var r = new Random().Next(500, 1500);
        Thread.Sleep(r);
        Console.WriteLine($"{id} finished in {r} ms");
    }
);
    threads[i] = t;
}

foreach (var t in threads)
{
    t.Start();
    t.Join();
}

// foreach (var t in threads)
// {
//     t.Join();
// }

sw.Stop();
var elapsed = sw.ElapsedMilliseconds;

Console.WriteLine($"elapsed: {elapsed} ms");

Upvotes: -1

Giorgi
Giorgi

Reputation: 30873

You can use WaitHandles to signal that a thread has completed working.

Upvotes: 0

Manfred
Manfred

Reputation: 5656

Make each thread start the next one.

However, if they all run in sequence anyways, what is the reason you want to use multiple threads in the first place?

Upvotes: 1

Itay Karo
Itay Karo

Reputation: 18286

What Possible reason you have to that? if you don't need the, to run in parallel why do you need 3 threads?

Any way - you can call thread1.Join() from thread2 and thread2.Join() from thread3 so each thread will wait for the previous one.

Upvotes: 3

Marcus Johansson
Marcus Johansson

Reputation: 2667

The simplest way is just to have a small sleep between the startups, that is how I "solved" the problem.

Another option is to start tr2 from tr1, and tr3 from tr2, after you've done the non thread-safe things.

How are they dependent on each other? Why don't you just have one thread?

Upvotes: 0

Related Questions