Display Progress Bar While Doing Some Work in C#

Display progress bar while doing some work in C#?

It seems to me that you are operating on at least one false assumption.

1. You don't need to raise the ProgressChanged event to have a responsive UI

In your question you say this:

BackgroundWorker is not the answer
because it may be that I don't get the
progress notification, which means
there would be no call to
ProgressChanged as the DoWork is a
single call to an external function .
. .

Actually, it does not matter whether you call the ProgressChanged event or not. The whole purpose of that event is to temporarily transfer control back to the GUI thread to make an update that somehow reflects the progress of the work being done by the BackgroundWorker. If you are simply displaying a marquee progress bar, it would actually be pointless to raise the ProgressChanged event at all. The progress bar will continue rotating as long as it is displayed because the BackgroundWorker is doing its work on a separate thread from the GUI.

(On a side note, DoWork is an event, which means that it is not just "a single call to an external function"; you can add as many handlers as you like; and each of those handlers can contain as many function calls as it likes.)

2. You don't need to call Application.DoEvents to have a responsive UI

To me it sounds like you believe that the only way for the GUI to update is by calling Application.DoEvents:

I need to keep call the
Application.DoEvents(); for the
progress bar to keep rotating.

This is not true in a multithreaded scenario; if you use a BackgroundWorker, the GUI will continue to be responsive (on its own thread) while the BackgroundWorker does whatever has been attached to its DoWork event. Below is a simple example of how this might work for you.

private void ShowProgressFormWhileBackgroundWorkerRuns() {
// this is your presumably long-running method
Action<string, string> exec = DoSomethingLongAndNotReturnAnyNotification;

ProgressForm p = new ProgressForm(this);

BackgroundWorker b = new BackgroundWorker();

// set the worker to call your long-running method
b.DoWork += (object sender, DoWorkEventArgs e) => {
exec.Invoke(path, parameters);
};

// set the worker to close your progress form when it's completed
b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
if (p != null && p.Visible) p.Close();
};

// now actually show the form
p.Show();

// this only tells your BackgroundWorker to START working;
// the current (i.e., GUI) thread will immediately continue,
// which means your progress bar will update, the window
// will continue firing button click events and all that
// good stuff
b.RunWorkerAsync();
}

3. You can't run two methods at the same time on the same thread

You say this:

I just need to call
Application.DoEvents() so that the
Marque progress bar will work, while
the worker function works in the Main
thread . . .

What you're asking for is simply not real. The "main" thread for a Windows Forms application is the GUI thread, which, if it's busy with your long-running method, is not providing visual updates. If you believe otherwise, I suspect you misunderstand what BeginInvoke does: it launches a delegate on a separate thread. In fact, the example code you have included in your question to call Application.DoEvents between exec.BeginInvoke and exec.EndInvoke is redundant; you are actually calling Application.DoEvents repeatedly from the GUI thread, which would be updating anyway. (If you found otherwise, I suspect it's because you called exec.EndInvoke right away, which blocked the current thread until the method finished.)

So yes, the answer you're looking for is to use a BackgroundWorker.

You could use BeginInvoke, but instead of calling EndInvoke from the GUI thread (which will block it if the method isn't finished), pass an AsyncCallback parameter to your BeginInvoke call (instead of just passing null), and close the progress form in your callback. Be aware, however, that if you do that, you're going to have to invoke the method that closes the progress form from the GUI thread, since otherwise you'll be trying to close a form, which is a GUI function, from a non-GUI thread. But really, all the pitfalls of using BeginInvoke/EndInvoke have already been dealt with for you with the BackgroundWorker class, even if you think it's ".NET magic code" (to me, it's just an intuitive and useful tool).

Best way to display a progress form while a method is executing code?

A BackgroundWorker is a great way to perform a long running operation without locking the UI thread.

Use the following code to start a BackgroundWorker and display a loading form.

// Configure a BackgroundWorker to perform your long running operation.
BackgroundWorker bg = new BackgroundWorker()
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

// Start the worker.
bg.RunWorkerAsync();

// Display the loading form.
loadingForm = new loadingForm();
loadingForm.ShowDialog();

This will cause the following method to be executed on a background thread. Note that you cannot manipulate the UI from this thread. Attempting to do so will result in an exception.

private void bg_DoWork(object sender, DoWorkEventArgs e)
{
// Perform your long running operation here.
// If you need to pass results on to the next
// stage you can do so by assigning a value
// to e.Result.
}

When the long running operation completes, this method will be called on the UI thread. You can now safely update any UI controls. In your example, you would want to close the loading form.

private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Retrieve the result pass from bg_DoWork() if any.
// Note, you may need to cast it to the desired data type.
object result = e.Result;

// Close the loading form.
loadingForm.Close();

// Update any other UI controls that may need to be updated.
}

Implementing backgroundworker to display progress bar in another form

You can't set control properties on a form from a different thread. You need an invokation to do this.

On your form, create a function:

public void SetProgressText(string value) {
if (this.InvokeRequired) {
Action<string> progressDelegate = this.SetProgressText;
progressDelegate.Invoke(value);
} else {
label_Progression.Text = value;
}
}

And then, instead of

f_p.label_Progression.Text = "Call to exe";

call

f_p.SetProgressText("Call to exe");

Same for the progress bar. You can put all invokations inside one function though.

C# I need progress bar to work while UI makes com call

You should create separate thread for execution of method call which takes time. Until it returns required data, show progress bar on your UI thread. This should work fine.

i.e. You should select first option from suggested three.

Progress bar in console application

This line is your problem:

drawTextProgressBar(0, totalCount);

You're saying the progress is zero in every iteration, this should be incremented. Maybe use a for loop instead.

for (int i = 0; i < filePath.length; i++)
{
string FileName = Path.GetFileName(filePath[i]);
//copy the files
oSftp.Put(LocalDirectory + "/" + FileName, _ftpDirectory + "/" + FileName);
//Console.WriteLine("Uploading file..." + FileName);
drawTextProgressBar(i, totalCount);
}

Update progress bar in another form while task is running

Create your progress bar form on the main UI thread of the parent form, then call the Show() method on the object in your button click event.

Here's an example with 2 bars:

//In parent form ...
private MyProgressBarForm progressBarForm = new MyProgressBarForm();

private void button1_Click(object sender, EventArgs e)
{
progressBarForm.Show();
Task task = new Task(RunComparisons);
task.Start();
}

private void RunComparisons()
{
for (int i = 1; i < 100; i++)
{
System.Threading.Thread.Sleep(50);
progressBarForm.UpdateProgressBar(1, i);
}
}

//In MyProgressBarForm ...
public void UpdateProgressBar(int index, int value)
{
this.Invoke((MethodInvoker) delegate{
if (index == 1)
{
progressBar1.Value = value;
}
else
{
progressBar2.Value = value;
}
});
}

How to show progress bar while reading multiple text files

Do you want to show progress for each file itself or for all files in one?

You can get your file size with:

FileInfo fileInfo = new FileInfo(file);
long fileLength = fileInfo.Length;

Set your progress bar minimum to 0 and maximum to 100.
Create a variable containing the current stream position and then update your progress bar with:

(int)(((decimal)currentStreamPosition / (decimal)fileLength)*(decimal)100);

You can either add all file sizes and show percentage or set the currentStreamPosition to zero when finished reading one file.

You have to traverse all files you need to read before getting the exact file size in sum.



Related Topics



Leave a reply



Submit