Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# -Threading - Execution Order

When I execute threads th1,th2 and th3.They are executing one after another.How do i change my code so that the execution order is not predictable .(Without using Random).

public class Test
{
    static void Main()
    {

        Person p = new Person();
        p.Id = "cs0001";
        p.Name = "William";

        Thread th1 = new Thread(()=>ProcessOne(p));
        th1.Name = "ThreadOne";
        th1.Start();

        Thread th2 = new Thread(()=>ProcessTwo(p));
        th2.Name = "ThreadTwo";
        th2.Start();

        Thread th3 = new Thread(()=> ProcessThree(p));
        th3.Name = "ThreadThree";
        th3.Start();

        Console.ReadKey(true);
    }

    static void ProcessOne(Person p)
    {
         Console.WriteLine("Thread {0} is executing", 
         Thread.CurrentThread.Name);
          Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
    }

    static void ProcessTwo(Person p)
    {
        Console.WriteLine("Thread {0} is executing",
        Thread.CurrentThread.Name);
        Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
    }

    static void ProcessThree(Person p)
    {
        Console.WriteLine("Thread {0} is executing",
        Thread.CurrentThread.Name); 
        Console.WriteLine("Id :{0},Name :{1}", p.Id, p.Name);
    }
}

public class Person
{

    public string Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

}
like image 545
user215675 Avatar asked Jul 31 '26 15:07

user215675


1 Answers

In your code the order of execution is not predictable. The reason you see sequential calls is because your methods do very little work and by the time you start the next thread the first already finished. By the way when I ran your code I got this result:

Thread ThreadOne is executing
Thread ThreadTwo is executing
Id :cs0001,Name :William
Thread ThreadThree is executing
Id :cs0001,Name :William
Id :cs0001,Name :William

One can clearly see that the methods execute in parallel. Running the program multiple times you will get different results.

like image 120
Darin Dimitrov Avatar answered Aug 02 '26 04:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!