Reputation: 183
I have a method which creates different number of requests according to user's input. For each input I have to create an instance of an object and run method from that object in new thread. It means I never know, how many threads I will need. And later I will have to access data from each instance that I created before.
So the question is: How can I create different number of requests (and for each request one thread) according to user's input?
An example:
userInput = [start, end, start2, end2, start3, end3]
//for each pair Start-end create instance with unique name or make it other way accessible
Request req1 = new Request('start', 'end')
Request req2 = new Request('start2', 'end2')
Request req3 = new Request('start3', 'end3')
//create thread for each instance
Thread t1 = new Thread(new ThreadStart(req1.GetResponse));
t1.Start();
Thread t2 = new Thread(new ThreadStart(req2.GetResponse));
t2.Start();
Thread t3 = new Thread(new ThreadStart(req3.GetResponse));
t3.Start();
//get data from each instance
string a = req1.result
string b = req2.result
string c = req3.result
Upvotes: 0
Views: 658
Reputation: 9387
You should NOT create a new thread per Request
. Instead take advantage of the ThreadPool
, either by using TPL, PLINQ or ThreadPool.QueueUserWorkItem
.
An example of how you could do it with PLINQ:
public static class Extensions
{
public static IEnumerable<Tuple<string, string>> Pair(this string[] source)
{
for (int i = 0; i < source.Length; i += 2)
{
yield return Tuple.Create(source[i], source[i + 1]);
}
}
}
class Program
{
static void Main(string[] args)
{
var userinput = "start, end, start2, end2, start3, end3, start4, end4";
var responses = userinput
.Replace(" ", string.Empty)
.Split(',')
.Pair()
.AsParallel()
.Select(x => new Request(x.Item1, x.Item2).GetResponse());
foreach (var r in responses)
{
// do something with the response
}
Console.ReadKey();
}
}
Upvotes: 1
Reputation: 564811
In .NET 4, this could be done via Task<T>
. Instead of making a thread, you'd write this as something like:
Request req1 = new Request("start", "end");
Task<string> task1 = req1.GetResponseAsync(); // Make GetResponse return Task<string>
// Later, when you need the results:
string a = task1.Result; // This will block until it's completed.
You'd then write the GetRepsonseAsync
method something like:
public Task<string> GetRepsonseAsync()
{
return Task.Factory.StartNew( () =>
{
return this.GetResponse(); // calls the synchronous version
});
}
Upvotes: 2
Reputation: 1039398
If you are using .NET 3.5 or lower you could use the ThreadPool.QueueUserWorkItem method and if you are using .NET 4.0 use the TPL.
Upvotes: 1