I want to use multiple BackgroundWorkers for handling clients in a chat server (C#). But I don't know how to declare the multiple BackgroundWorkers. One backgroundworker for each client. I thought that maybe there is a way to declare them like this:
for(int counter=0; ; counter++) {
BackgroundWorker bw_counter=new BackgroundWorker();
bw_counter.RunWorkerAsync();
}
I want to replace "counter" in "bw_counter" with the actual value of "int counter". I don't know how to do this. Some people that have ideas?
I searched for a way to get it working but I couldn't thind a thread on SO that solves my problem.
What you are trying to do is pretty much the definition of an array (or IList
, at the very least).
var my_workers = new BackgroundWorker[counter];
Now you can refer to them by number:
my_workers[0] = new BackgroundWorker();
my_workers[0].RunWorkerAsync();
A simple way to create the array using your original code:
var workers = Enumerable.Range(0, counter)
.Select(_ => {
var bw = new BackgroundWorker();
bw.RunWorkerAsync();
return bw; })
.ToArray();