Hi,
I have a WinForm application, when the Form load, I would like to create 2
worker threads that will load data from different SQL tables and populate 2
ListBoxes on the form.
Here is what I wantto do: change the cursor to hourglass when the first
worker thread starts and return the cursor to normal when both worker
threads end. But I don't know how to do it.
TIA
Marc Gravell - 11 Mar 2008 09:01 GMT
Following shows an example that starts 2 workers, sets the cursor when
both have exited, and demonstrates jumping back to the UI thread to
perform the actual UI update (you can't touch the UI from the worker
thread):
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Application.Run(new MyForm());
}
}
class MyForm : Form
{
BackgroundWorker worker1, worker2;
public MyForm() { InitializeComponent(); }
private int busyCount = 0;
private void BeginBusy()
{
busyCount++;
if (busyCount > 0) this.Cursor = Cursors.WaitCursor;
}
private void EndBusy()
{
busyCount--;
if (busyCount <= 0) this.Cursor = Cursors.Default;
}
private void InitializeComponent()
{
worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(worker1_DoWork);
worker2 = new BackgroundWorker();
worker2.DoWork += new DoWorkEventHandler(worker2_DoWork);
}
void worker2_DoWork(object sender, DoWorkEventArgs e)
{
Invoke((MethodInvoker)BeginBusy);
Thread.Sleep(5000);
Invoke((MethodInvoker)delegate
{
// update UI
Text += "; worker 2 complete";
EndBusy();
});
}
void worker1_DoWork(object sender, DoWorkEventArgs e)
{
Invoke((MethodInvoker)BeginBusy);
Thread.Sleep(9000);
Invoke((MethodInvoker) delegate {
// update UI
Text += "; worker 1 complete";
EndBusy();
});
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
worker1.RunWorkerAsync();
worker2.RunWorkerAsync();
}
}
Marc Gravell - 11 Mar 2008 09:04 GMT
Actually my last post was unnecessarily complex - you don't really
need BackgroundWorker in this case...
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private int busyCount = 0;
private void BeginBusy()
{
busyCount++;
if (busyCount > 0) this.Cursor = Cursors.WaitCursor;
}
private void EndBusy()
{
busyCount--;
if (busyCount <= 0) this.Cursor = Cursors.Default;
}
void worker2_DoWork(object state)
{
Invoke((MethodInvoker)BeginBusy);
Thread.Sleep(5000);
Invoke((MethodInvoker)delegate
{
// update UI
Text += "; worker 2 complete";
EndBusy();
});
}
void worker1_DoWork(object state)
{
Invoke((MethodInvoker)BeginBusy);
Thread.Sleep(9000);
Invoke((MethodInvoker) delegate {
// update UI
Text += "; worker 1 complete";
EndBusy();
});
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ThreadPool.QueueUserWorkItem(worker1_DoWork);
ThreadPool.QueueUserWorkItem(worker2_DoWork);
}
}