Date: 03/15/08 (C Sharp) Keywords: no keywords I'm playing around with the BackgroundWorker class. Since I've never used it before I was hoping to get some critique. The code works fine but it's probably not using best practices (throughout). I'm using a form with a listbox, button, and timer. Please assume that 'Files' will never contain duplicate names. I don't think any lock() blocks are necessary but I might be wrong. using System; using System.Collections; using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace ThreadTest { public partial class Form1 : Form { private const int THREADMAX = 3; private ArrayList Files, Running; private BackgroundWorker[] Bgw; private Loader Ldr; public Form1() { InitializeComponent(); Files = new ArrayList(10); Bgw = new BackgroundWorker[THREADMAX]; Running = new ArrayList(THREADMAX); Ldr = new Loader(); for (int x = 0; x < 10; x++) { Files.Add(x.ToString()); } } private void button1_Click(object sender, EventArgs e) { string s; timer1.Start(); while (Files.Count != 0) { s = Files[0].ToString(); if (Running.Count < THREADMAX) { for (int x = 0; x < THREADMAX; x++) { if (Bgw[x] == null || !Bgw[x].IsBusy) { Bgw[x] = new BackgroundWorker(); Bgw[x].DoWork += new DoWorkEventHandler(Ldr.Load); Bgw[x].RunWorkerCompleted += new RunWorkerCompletedEventHandler(Done); listBox1.Items.Add("Loading " + s); Running.Add(s); Bgw[x].RunWorkerAsync(s); Files.Remove(s); break; } } } Application.DoEvents(); } } private void Done(object sender, RunWorkerCompletedEventArgs e) { Running.Remove(e.Result.ToString()); listBox1.Items.Add("Load complete for " + e.Result.ToString()); } private void timer1_Tick(object sender, EventArgs e) { if (Files.Count == 0 && Running.Count == 0) { listBox1.Items.Add("Done!"); timer1.Stop(); } } } public class Loader { public void Load(object sender, DoWorkEventArgs e) { e.Result = e.Argument.ToString(); Thread.Sleep(1000); } } } Thanks!
|