Shiro
Shiro

Reputation: 5

How to call threads before other threads?

I'm new to threading and don't quite understand the structuring of it.

class Program
{
    static void Main(string[] args)
    {
        Console.Read();
    }

    static void Gone()
    {
        for (int i = 0; i < 5; i++)
        {

            Console.WriteLine("Gone");
        }
    }

    static void Going()
    {
        for (int i = 0; i < 2; i++)
        {       
            Console.WriteLine("Going");
        }
    }
}
}

I am trying to alter the above code so that the main thread creates a thread calling the Gone method. Also, I want to alter the Gone method so it creates a thread to hit Going before it prints gone. I'm assuming a Join would be used in the latter of my problem but I don't know where to put threads or where to use a join ( I had the following code within the Main method but that only displayed the word "Gone" 5 times and not "Going".

Thread t = new Thread(Gone);
        t.Start();
        t.Join();

Upvotes: 0

Views: 44

Answers (2)

George Chondrompilas
George Chondrompilas

Reputation: 3237

I am not sure if I understand correctly but this is what I would do:

class Program
{
    static void Main(string[] args)
    {
        Thread thread2 = new Thread(new ThreadStart(Gone));

        thread2.Start();

        Console.Read();
    }

    static void Gone()
    {
        for (int i = 0; i < 5; i++)
        {


            Thread thread1 = new Thread(new ThreadStart(Going));
            thread1.Start();
            thread1.Join();
            Console.WriteLine("Gone");
        }
    }
    static void Going()
    {
        for (int i = 0; i < 2; i++)
        {       
            Console.WriteLine("Going");
        }
    }

Output:

Going Going Gone Going Going Gone Going Going Gone Going Going Gone Going Going Gone

This will run synchronously.

Upvotes: 1

XeroxDucati
XeroxDucati

Reputation: 5190

Typed but not compiled.. I think you want this -- you'll need to tweak a bit if it doesn't build/run, but it gives the general idea:

class Program
{
    static void Main(string[] args)
    {
        Run();
        Console.Read();
    }

    static async void Run()
    {
         await Gone();
    }

    static async void Gone()
    {
        for (int i = 0; i < 5; i++)
        {
            await Going();
            Console.WriteLine("Gone");
        }
    }

    static async void Going()
    {
        for (int i = 0; i < 2; i++)
        {       
            Console.WriteLine("Going");
        }
    }
}
}

Upvotes: 0

Related Questions