0
Posted on 8:13 AM by Softminer and filed under ,

Sometimes you need to do two different task and you want that the task do simultaneously or one task wait for other task to finish.

in the following example , there are three different Thread and when you join the Thread they will wait until all joined thread finished.

using System;
using System.Threading;

class MyThread
{
    public int count;
    public Thread thrd;
    public MyThread(string name)
    {
        count = 0;
        thrd = new Thread(this.run);
        thrd.Name = name;
        thrd.Start();
    }
    void run()
    {
        Console.WriteLine(thrd.Name + " starting.");
        do
        {
            Thread.Sleep(500);
            Console.WriteLine("In " + thrd.Name +
                              ", count is " + count);
            count++;
        } while (count < 10);

        Console.WriteLine(thrd.Name + " terminating.");
    }
}
class MainClass
{
    public static void Main()
    {
        Console.WriteLine("Main thread starting.");

        MyThread mt1 = new MyThread("Child #1");
        MyThread mt2 = new MyThread("Child #2");
        MyThread mt3 = new MyThread("Child #3");

        mt1.thrd.Join();
        Console.WriteLine("Child #1 joined.");

        mt2.thrd.Join();
        Console.WriteLine("Child #2 joined.");

        mt3.thrd.Join();
        Console.WriteLine("Child #3 joined.");
        
        ThreadStart mythred = new ThreadStart(test);
        Thread t = new Thread(mythred);
        t.Start();
        t.Join();

        Console.WriteLine("Main thread ending.");
    }

    private static void test()
    {
        Thread.Sleep(3000); 
        Console.WriteLine("My thread finished");
    }
}


for more information you can check here
0
Responses to ... Threading in C#