C# 通过列表初始化多个线程<;螺纹>;

C# 通过列表初始化多个线程<;螺纹>;,c#,multithreading,C#,Multithreading,我的问题是如何初始化一个线程列表,以及在这些线程中如何初始化一个像独立线程一样工作的线程函数。因为我每次都必须为每个线程创建新函数。您的代码似乎很奇怪。您不需要(也不应该)为每个线程定义一个方法。该方法定义了逻辑。线程执行逻辑;多个线程都可以运行相同的逻辑,这似乎是本例的要求 我建议您首先编写一个执行登录的async方法: Thread thread1 = new Thread(startThread1); Thread thread2 = new Thread(startThread2); T

我的问题是如何初始化一个线程列表,以及在这些线程中如何初始化一个像独立线程一样工作的线程函数。因为我每次都必须为每个线程创建新函数。

您的代码似乎很奇怪。您不需要(也不应该)为每个线程定义一个方法。该方法定义了逻辑。线程执行逻辑;多个线程都可以运行相同的逻辑,这似乎是本例的要求

我建议您首先编写一个执行登录的
async
方法:

Thread thread1 = new Thread(startThread1);
Thread thread2 = new Thread(startThread2);
Thread thread3 = new Thread(startThread3);


thread1.Start();
thread2.Start();
thread3.Start();
 }

void startThread1()
{
    int i = 0;
    int time = 500;
    System.Threading.Thread.Sleep(time);

    LoginUser(username[i], password[i], i);
     i = i + 1;
    time = time + 500;
    Thread.Yield();
}
void startThread2()
{
    int i = 0;
    int time = 500;
    System.Threading.Thread.Sleep(time);

    LoginUser(username[i], password[i], i);
     i = i + 1;
    time = time + 500;
    Thread.Yield();
}


 void startThread3()
{
    int i = 0;
    int time = 500;
    System.Threading.Thread.Sleep(time);

    LoginUser(username[i], password[i], i);
     i = i + 1;
    time = time + 500;
    Thread.Yield();
}
单独测试该方法,并确保它按照您希望的方式工作

一旦它开始工作,您需要弄清楚如何同时从多个执行“线程”调用它。通常不需要创建新线程或使用
ThreadStart
;相反,只需调用它并让它异步运行即可

要为三个用户中的每一个调用它,首先定义一个包含用户信息的数组:

public static async Task LogonUser(string userName, string password)
{
    Console.WriteLine("Logging on user {0} with password {1}", userName, password);
    //Do the actual logon work here
    await Task.Delay(500);  
    Console.WriteLine("Done logging on user {0}", userName);
}
只需选择使用LINQ的方法:

var userInfo = new []
{
    new { UserName = "User One",   Password = "1111" },
    new { UserName = "User Two",   Password = "2222" },
    new { UserName = "User Three", Password = "3333" }
};
输出:

var tasks = userInfo.Select
    (
        info => LogonUser(info.UserName, info.Password)
    );
await Task.WhenAll(tasks.ToArray());

不清楚你想浇什么,而不是还有。它也可以使用。我已经编辑它,使它更清楚!感谢@行动代表!将尝试
Logging on user User One with password 1111
Logging on user User Two with password 2222
Logging on user User Three with password 3333
Done logging on user User Three
Done logging on user User One
Done logging on user User Two