The goal is to pick items from a listview, do some web related task with the information and then update the UI with the returned information from the web request.
The problem is with having multiple list view items processed at once, me being a newbie to C#, i came up with this code, I'm pretty sure this is not good, i just came up with it, is there a better way to get this done ?
Dictionary<String,BackgroundWorker> worker_list = new Dictionary<String, BackgroundWorker>();
int completed_count = 0;
int total_work;
public Form1()
{
InitializeComponent();
}
public void worker(String woker_id)
{
WebClient client = new WebClient();
byte[] response =
client.UploadValues("http://google.com", new NameValueCollection() { });
worker_list[woker_id].ReportProgress(100);
if(completed_count != total_work){
worker(woker_id);
}
}
// Adding the work to the que since a thread can't access background Ui thread
private void button2_Click(object sender, EventArgs e)
{
// preparing task list
txtOutput.Text += "Total stuff to run" + listView1.Items.Count + Environment.NewLine + Environment.NewLine;
// check for valid input
int value;
if (!int.TryParse(textBox1.Text, out value) || textBox1.Text == "0"){
MessageBox.Show("invalid number of threads");
return;
}
// create threads
for (int i = 0; i < value; i++)
{
String woker_id = "bg_" + i.ToString();
worker_list[woker_id] = new BackgroundWorker();
worker_list[woker_id].WorkerSupportsCancellation = true;
worker_list[woker_id].WorkerReportsProgress = true;
// Intiial message
txtOutput.Text += "Worker " + woker_id + " Started" + Environment.NewLine;
worker_list[woker_id].DoWork += delegate {
worker(woker_id);
};
worker_list[woker_id].ProgressChanged += delegate {
if(completed_count == total_work) {
return;
}else
{
txtOutput.Text += "Worker " + woker_id + "is running again" + Environment.NewLine;
}
listView1.Items[completed_count].BackColor = Color.LightGreen;
completed_count++;
};
worker_list[woker_id].RunWorkerCompleted += delegate {
worker_list[woker_id].CancelAsync();
worker_list.Remove(woker_id);
txtOutput.Text += "Worker " + woker_id + " Completed | Thread count = " + worker_list.Count() + Environment.NewLine;
};
worker_list[woker_id].RunWorkerAsync();
}
// Line spacing
txtOutput.Text += Environment.NewLine + Environment.NewLine;
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i < 11; i++)
{
Random rnd = new Random();
ListViewItem item = new ListViewItem("Item " + i);
// Sleep Time
item.SubItems.Add((rnd.Next(100,500) * i).ToString());
listView1.Items.Add(item);
}
// setting up the total work
total_work = listView1.Items.Count;
}
Thank you.
TPL
\$\endgroup\$