C#-Threading - 执行顺序

use*_*675 2 c# multithreading

当我执行线程th1,th2和th3时,它们一个接一个地执行.如何更改我的代码,以便执行顺序不可预测.(不使用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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 9

在您的代码中,执行顺序是不可预测的.您看到顺序调用的原因是因为您的方法执行的工作很少,并且当您启动第一个已完成的下一个线程时.顺便说一句,当我运行你的代码时,我得到了这个结果:

Thread ThreadOne is executing
Thread ThreadTwo is executing
Id :cs0001,Name :William
Thread ThreadThree is executing
Id :cs0001,Name :William
Id :cs0001,Name :William
Run Code Online (Sandbox Code Playgroud)

可以清楚地看到方法并行执行.多次运行程序会得到不同的结果.