ProgressBar and DoEvents

Trips

Well-known member
Joined
Aug 7, 2010
Messages
2,788
I made a simple application to reflect my current problem. The application first brings up a form to ask the user for information but for this example, the user just selects the OK button After that, I run a simulation for a long
time and I would like to show the status of the the progress with a ProgressBar. I also want the ability to stop the simulation by allowing the user to hit a Cancel button. I have this working but I am using DoEvents which I have read on these
forums is not a good idea. In the my real application, the DoEvents eats up some time away from the simulation which I would like to avoid. I have tried using a BackgrounderWorker thread but since the simulation does not reside in a form,
I cant figure out how to make that work. I also made a thread for the simulation but did not get that to work without using DoEvents.
So the question is, "Can I get this to work without using DoEvents?".
Here is the Program.cs file.
<pre>using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestProgressBar
{
static class TestProgessBarProgram
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

TestProgessBarForm form = new TestProgessBarForm();

if (form.ShowDialog() == DialogResult.OK)
{
TestProgressBarMain();
}
}

static void TestProgressBarMain()
{
ProgressBarForm form = new ProgressBarForm();

int min = 0;
int max = 1000;

form.SetProgressValue(min, min, max);
form.Show();

bool loop = true;

for (int index = min; loop && index < max; index++)
{
System.Threading.Thread.Sleep(1);

form.SetProgressValue(index, min, max);

Application.DoEvents();

if (form.userRequestStop)
{
loop = false;
}
}

return;
}
}
[/code]
Here is the ProgressBar code.
<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestProgressBar
{
public partial class ProgressBarForm : Form
{
public bool userRequestStop = false;

public ProgressBarForm()
{
InitializeComponent();
}

private void Cancel_Click(object sender, EventArgs e)
{
userRequestStop = true;
}

public void SetProgressValue(int value, int min, int max)
{
progressBar1.Minimum = min;
progressBar1.Maximum = max;
progressBar1.Value = value;
}

protected override void OnClosed(EventArgs e)
{
userRequestStop = true;

base.OnClosed(e);
}
}
}[/code]

View the full article
 
Back
Top