views:

78

answers:

5

use ThreadPool.QueueUserWorkItem (WaitCallback, Object) to start a thread with my target method and data. Can I pass more than one data into my method? the second parameter in QueueUserWorkItem (WaitCallback, Object) can be an array?

+3  A: 

Yes the type of the argument is System.Object so you can pass anything. http://msdn.microsoft.com/en-us/library/4yd16hza.aspx

btlog
+1  A: 

All types in .NET derive from object so you can pass in anything you want to QueueUserWorkItem. Just cast it in your WaitCallback method.

Jake Pearson
+4  A: 

The second parameter can be an array but you're better off creating a custom class for containing your data. That way the data you pass is fully typed.

Sam
+2  A: 

Just cast your state object back, which also applies for ParameterizedThreadStart:

List<string> list = new List<string> {"1","2","3"};
ThreadPool.QueueUserWorkItem (CallBack, list);

void CallBack(object state)
{
    List<string> list = (List<string>) state;
}
Chris S
+1  A: 

Here is a example of using a class so you can get strongly typed pramaters

ThreadPool.QueueUserWorkItem(new WaitCallback(RemoteUserManagerClient.CreateUser),
    new CreateUserTaskInfo(Program.Context, remote, user, password, SqlInstancePath, AccountID, practiceName));

public class CreateUserTaskInfo
{
    public PrincipalContext context;
    public string username;
    public string password;
    public string sqlServer;
    public string database;
    public string practice;
    public RemoteUserManager client;
    public CreateUserTaskInfo(PrincipalContext con, RemoteUserManager cli, string usr, string pass, string sql, string db, string prac)
    {
        client = cli;
        context = con;
        username = usr;
        password = pass;
        sqlServer = sql;
        database = db;
        practice = prac;
    }
}
static public void CreateUser(object stateInfo)
{
    CreateUserTaskInfo ti = (CreateUserTaskInfo)stateInfo;
    lock (userLock)
    {
        if (UserPrincipal.FindByIdentity(ti.context, ti.username) == null)
        {
            using (UserPrincipal u = new UserPrincipal(ti.context, ti.username, ti.password, true))
            {

                u.PasswordNeverExpires = true;
                u.UserCannotChangePassword = true;
                u.Save();

                using (GroupPrincipal g = GroupPrincipal.FindByIdentity(ti.context, "Remote Desktop Users"))
                {
                    g.Members.Add(u);
                    g.Save();
                }
            }
        }
    }
    lock (editLock)
    {
        ti.client.Edit(ti.username, null, ti.sqlServer, ti.database, ti.practice);
    }

}
Scott Chamberlain