C#使用ThreadPool时,我可以将多个数据传递给我的目标方法吗?

5Yr*_*DBA 5 c# multithreading threadpool queueuserworkitem

用于使用ThreadPool.QueueUserWorkItem (WaitCallback, Object)我的目标方法和数据启动一个线程.我可以将多个数据传递给我的方法吗?第二个参数QueueUserWorkItem (WaitCallback, Object)可以是数组吗?

Sco*_*ain 3

这是使用类的示例,以便您可以获得强类型的语法

public class CreateUserTaskInfo
{
    public string username { get; };
    public string password { get; };
    public string sqlServer { get; };
    public string database { get; };
    public string practice { get; };
    public RemoteUserManager client { get; };
    public CreateUserTaskInfo(RemoteUserManager cli, string usr, string pass, string sql, string db, string prac)
    {
        client = cli;
        username = usr;
        password = pass;
        sqlServer = sql;
        database = db;
        practice = prac;
    }
}

public void ExampleFunction(...)
{
    //gather up the variables to be passed in
    var taskInfo = new CreateUserTaskInfo(remote, user, password, SqlInstancePath, AccountID, practiceName);

    //queue the background work and pass in the state object.
    ThreadPool.QueueUserWorkItem(new WaitCallback(RemoteUserManagerClient.CreateUser), taskInfo);
}

static public void CreateUser(object stateInfo)
{
    CreateUserTaskInfo ti = (CreateUserTaskInfo)stateInfo;

    //use ti in the method and access the properties, it will be 
    // the same object as taskInfo from the other method
}
Run Code Online (Sandbox Code Playgroud)