I'm trying to convert my single thread function into a multithreaded function. I've been reading up on threading, but I'm unsure of the proper structure needed to be able to start a thread for each server in the array while at the same time waiting for the threads to finish and receiving a return value from each one before being able to parse the return value data.
So the order of operations should be
- Start a new thread for each server name
- Each thread when it ends should receive an output from the function runPowerShellScript(server))
- Wait for each thread to end and then organize the data. If I have 5 servers, I will have 5 different variables with return values
Also, how does the OS/compiler handle a situation like this where the return variable (returnVal) name is the same with each thread opened? I understand this is probably basic for someone who was classroom taught, since I am self taught I'm not sure what to do.
private void Run_Click(object sender, EventArgs e)
{
string[] servers = { "server1", "server2", "server3", "server4", "server5" };
foreach (string server in servers)
{
Collection<PSObject> returnVal = new Collection<PSObject>();
Thread psquery = new Thread(() => returnVal = runPowerShellScript(server)); // lambda expression assigns return value to function
psquery.Start();
psquery.Join(); // waits for thread to finish
}
// process data here
}