通过LIST <threads>初始化多个线程

时间:2016-08-12 11:31:42

标签: c# multithreading

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();
}

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

1 个答案:

答案 0 :(得分:0)

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

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

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);
}

分别测试该方法,并确保它以您希望的方式工作。

一旦工作,就需要弄清楚如何同时从多个“线程”中调用它。通常,没有必要创建新线程或使用ThreadStart;相反,只需调用它并使其异步运行即可。

要为您的三个用户分别调用它,请首先定义一个包含用户信息的数组:

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

然后使用LINQ选择方法:

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

Example on DotNetFiddle