Program locks up when reading RSS feed - c#

I've made myself a class that reads RSS feeds and returns them to my main class. The code that I use for this is:
public List<Post> getLatestPosts()
{
this.rssReader = new XmlTextReader(this.rssUrl);
this.rssDoc = new XmlDocument();
// Load the XML content into rssDoc
rssDoc.Load(rssReader);
// ... other code to parse XML ... //
}
Now, when I call getLatestPosts() my application locks up for a few seconds. I'm assuming it's because that's how long it takes for the application to request the RSS feed (network latency and so forth).
I want to change this so my program doesn't lock up, and instead just waits for the response. I had the idea of using threads in my main form, but I'm confused about how I can capture whatever RSS data getLatestPosts() gets.
If I do this in my button click on my main form:
private void bGetLatestPosts_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(rssReader.getLatestPosts()));
}
I'm not capturing anything that getLatestPosts() returns.
I'm completely new to threads (this is mostly just me messing around to try and learn them) but I do have some experience in C#.
Thanks.

I'm assuming you are writing a WinForms application. There are two important rules for writing responsive WinForms applications:
Everything you do on the do on the main UI thread should complete quickly.
You can't access controls from any thread other than the main thread.
To solve your problem, run your code in a BackgroundWorker.
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.
To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
Here's some code that might help you:
private void bGetLatestPosts_Click(object sender, EventArgs e)
{
bGetLatestPosts.Enabled = false;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = getLatestPosts();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
// Handle exception...
}
else
{
List<Post> result = (List<Post>)e.Result;
// Update GUI...
}
bGetLatestPosts.Enabled = true;
}

Related

Background worker does not Work WPF

In my WPF program it took huge processing time and freezing for long time.
so I decided to use background worker and process it in background.
but it does not work. through debug, the program stop at Render3D(). It does not throw exception. Its like when you put return.
In other word it does nothing after reaching Render3D() and will just return.
(I don't say it will return Because im not sure but the behavior is same as return)
private readonly BackgroundWorker backgroundWorker = new BackgroundWorker();
private AssetDeclaration _assetDeclaration = new AssetDeclaration();
public MainWindow()
{
backgroundWorker.DoWork += backgroundWorker1_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 1000; i++)
{
if (!((BackgroundWorker)sender).CancellationPending)
{
Render3D(); // will return at this point. (why?) or waiting for something to start?
((BackgroundWorker)sender).ReportProgress(i);
}
else
{
e.Cancel = true;
break;
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done!");//will show message box instant.
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar1.Value = e.ProgressPercentage;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//...Some work here before starting Hard job!
//...From now i want to start heavy process in background.
//...with report to progress bar at same time.
backgroundWorker.RunWorkerAsync(100);
}
Render3D() works fine without Background processing but will freeze for some time.
Render3D() is in Partial class of MainWindow .because there are lots of methods so i decided to separate them.
Also how can I use ReportProgress outside backgroundWorker1_DoWork . for example in Render3D().
Last thing : i want to know how to show the user how much of process is done.
Solved!:
The problem was because i set Viewport3D inside Render3D()
I separated it from Render3D and problem got fixed. thanks to Henk Holterman for the right answer.
It seems some tasks cant be done in another Thread. with the Error report i find out that the invalid task is setting Viewport3D properties.
this tasks must be done in Main thread.
below is invalid Code that made background worker stop functioning.
DefineCamera();
Viewport.Children.Add(model); // Must be run in Main thread.
And this Part.
private void DefineCamera()
{
PerspectiveCamera camera = new PerspectiveCamera
{
FieldOfView = 60
};
PositionCamera(camera);
Viewport.Camera = camera; // Must be run in Main thread.
}
First of all, you had trouble finding the error.
... the program stop at Render3D(). It does not throw exception. Its like when you put return.
What actually happened was that an exception was thrown by your method and was captured by the Backgroundworker. It is transferred to the Completed event but you do have to act on it there.
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
// use the result(s) on the UI thread
}
// general cleanup
}
Failing to look at either e.Error or e.Result is the same as having an empty catch{} block in your program.
And with error handling in place we then have
oh yes it shown Error. System.InvalidOperationException the calling thread cannot access this object because a different thread owns it
This indicates that your Render3D() still interacts with the GUI somewhere.
The basic advice is to separate all the calculation (and I/O, database) work from the UI work. You can run the CPU bound and I/O bound cod in a thread but the GUI is single threaded, you can only interact with it from the main Thread.
In the world of WPF, unlike Windows Forms that you were used to, you should consider Dispatcher. To do this, you have to import System.Windows.Threading
private void ThreadTask()
{
Thread.Sleep(TimeSpan.FromSeconds(5));
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
//Do some heavy task here...
});
}
Quick Update
In order to run the thread from a button click or whatever, any function, add this line of code:
Thread thread = new Thread(new ThreadStart(ThreadTask));
thread.Start();
This line of code is equivalent to BackgroundWorker.RunWorkerAsync();
I would highly recommend using async/await. This feature was introduced in .NET 4.5, and is used to shift work off the main WPF GUI thread to make the application fast and responsive.
Essentially, the rule is to push any calculations which do not interact with GUI onto a background thread using a combination of Task.Run and async/await. Together with Dispatcher.Invoke, you don't really need anything else.
For example, a slow data call that might fetch data from the database could be pushed onto a background thread, so the application does freeze while it waits for the SQL to execute.
I've used this to make the applications that I write fast, responsive and snappy.

File Dialog from a Background Worker

While maintaining some code, I discovered that we have an infinite hang-up in a background worker. The worker requires access to a script file. The original code was written to pop up a file dialog if no script file was defined, to allow the user to select one. It looks something like this:
private void bgworker_DoWork(object sender, DoWorkEventArgs e)
{
... snip ...
if (String.IsNullOrWhitespace(scriptFile))
{
scriptFile = PromptForScript();
}
... snip ...
}
private string PrompForScript()
{
string script = "";
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
script = openDialog.FileName;
}
return script;
}
I've read up a bit about MethodInvoker, but almost all of the invoke methods require that you call them from a control. The background worker in question is running from a separate class, which doesn't extend Control. Do I use the form that calls the class with the bgworker for that? Or is there another way of interrupting the thread for user input?
It's not recommended to invoke the UI from the background worker DoWork event handler. BackgroundWorker is meant to do work on a non-UI thread to keep the UI responsive. You should ask for any file information before starting the BackgroundWorker object with RunWorkerAsync.
What you want to do is capture the SynchronizationContext on the UI thread and pass that along to the background worker. The BackgroundWorker can call Send() (synchronous, like Invoke) and Post() (asynchronous, like BeginInvoke) on the context to invoke back to the correct UI thread. That said, there is probably no need for the BackgroundWorker in this case- a regular threadpool thread would do just fine.
This (slightly modified) block of code from http://msmvps.com/blogs/manoj/archive/2005/11/03/74120.aspx should give you the general idea:
private void button1_Click(object sender, EventArgs e)
{
// Here we are on the UI thread, so SynchronizationContext.Current
// is going to be a WindowsFormsSynchronizationContext that Invokes properly
ctx = SynchronizationContext.Current;
ThreadPool.QueueUserWorkItem(
// This delegate is going to be invoked on a background thread
s => {
// This uses the context captured above to invoke
// back to the UI without the "messy" referencing
// of a particular form
ctx.Send(s2 =>
{
// Interact with your UI here- you are on the UI thread
},null);
}
);
}
If some Form kicks off a long-running process within another class that uses a BGworker, why wouldn't the form (or presenter, depending on UI architecture) handle the processing of the error state?
Perhaps, just pass back some status result (or throw a very targeted, specific exception that you can handle in the UI)?
Leave the background worker to determine if there IS an error, but leave handing the error (especially the UI portion of showing a message box) to the upper layers.
Sorry this didn't have more concrete code but it could go a lot of different ways depending on how your system is architected.
Well, the Form class has an Invoke method, so passing the form instance to the background working class should work.

BackgroundWorkerCompleted doesnt seem to run in main thread?

I'm writing a addin for outlook which has some network code for API calls, which is why I have several classes extending the BackgroundWorker class, each encapsulating a API call. The code looks like this for a Api Call:
public class ApiLogin : BackgroundWorker
{
private void ThisAddInStartup(object sender, EventArgs e)
{
this.DoWork += BgWorkerDoWork;
this.RunWorkerCompleted += BgWorkerCompleted;
}
private void BgWorkerDoWork(object sender, DoWorkEventArgs e)
{
//Perform network call on the background thread
var logged_in = ApiRequests.login();
e.Result = logged_in;
}
//This should run in the main thread, no?
private void BgWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var logged_in = (bool)e.Result;
//Do stuff in main thread, hopefully..
//Investigate if this runs in the main thread since it should block Outlook, no?
Thread.Sleep(50000);
}
}
And the code looks like this for my Outlook Addin:
public class ThisAddin
{
private ApiLogin _loginWorker;
private void ThisAddInStartup(object sender, EventArgs e)
{
_loginWorker = new ApiLogin();
_loginWorker.RunWorkerAsync();
}
}
When I run my addin I expect outlook to block for 50 seconds since I have a Thread.Sleep(50000) in the background workers Completed-event handler, but this does not happen. This implies to me that this code does not run in the main thread? I have searched for a solution in vain and now I would like to know if anyone here knows what might be the problem?
BackgroundWorker requires a synchronization provider to determine on which thread the RunWorkerCompleted event runs. It uses SynchronizationContext.Current. Odds are very high that this property is null when your plugin starts. So nothing is getting synchronized and the event runs on a threadpool thread.
There are two synchronization providers in the .NET framework, respectively the one for Winforms and the one for WPF. They need their respective message loop to do the thread marshaling, they assign SynchronizationContext.Current in their Application.Run() method. You have neither. The simplest solution is to create a Winforms Form and call its ShowDialog() method. That in itself already blocks the Outlook user interface. Also good to provide some feedback to the user so she doesn't have to guess why Outlook stopped responding.
I would certainly expect it to run on the same thread as the ThisAddinStartup method: you can verify this by tracing the thread id in both places.
As for Outlook, maybe it's running your add-in on a separate UI thread.

Reusing a BackgroundWorker, cancel and wait for it

Suppose you have a search textbox and have a search algorithm attached to the TextChanged event, that runs with a BackgroundWorker. If there comes a new character in the textbox, i need to cancel the previous search and run it again.
I tried using events in between the main thread and the bgw, from this previous question, but I still get the error "currently busy and cannot run multiple tasks concurrently"
BackgroundWorker bgw_Search = new BackgroundWorker();
bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
private void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchWithBgw();
}
private void SearchWithBgw()
{
// cancel previous search
if (bgw_Search.IsBusy)
{
bgw_Search.CancelAsync();
// wait for the bgw to finish, so it can be reused.
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
// start new search
bgw_Search.RunWorkerAsync(); // error "cannot run multiple tasks concurrently"
}
void bgw_Search_DoWork(object sender, DoWorkEventArgs e)
{
Search(txtSearch.Text, e);
}
private void Search(string aQuery, DoWorkEventArgs e)
{
int i = 1;
while (i < 3) // simulating search processing...
{
Thread.Sleep(1000);
i++;
if (bgw_Search.CancellationPending)
{
_resetEvent.Set(); // signal that worker is done
e.Cancel = true;
return;
}
}
}
EDIT To reflect answers. DonĀ“t reuse the BackgroundWorker, create a new one:
private void SearchWithBgw()
{
if (bgw_Search.IsBusy)
{
bgw_Search.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
bgw_Search = new BackgroundWorker();
bgw_Search.WorkerSupportsCancellation = true;
bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
}
bgw_Search.RunWorkerAsync();
}
When the _resetEvent.WaitOne() call completes, the worker thread isn't actually done. It is busy returning from DoWork() and waiting for an opportunity to run the RunWorkerCompleted event, if any. That takes time.
There is no reliable way to ensure the BGW is completed in a synchronous way. Blocking on IsBusy or waiting for the RunWorkerCompleted event to run is going to cause deadlock. If you really want to use only one bgw then you'll have to queue the requests. Or just don't sweat the small stuff and allocate another bgw. They cost very little.
Create a new background worker if the old one exists.
private void SearchWithBgw()
{
// cancel previous search
if (bgw_Search.IsBusy)
{
bgw_Search.CancelAsync();
// wait for the bgw to finish, so it can be reused.
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
BackgroundWorker bgw_Search = new BackgroundWorker();
bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
}
// start new search
bgw_Search.RunWorkerAsync(); // error "cannot run multiple tasks concurrently"
}
Also I know you put fake code in, but you want to make sure you set _resetEvent when the code completes normally too.
Do not reuse a Backgroundworker. It is a cheap resource, it is not a Thread.
make sure your Bgw code stops, yours looks OK. The Bgw will release the Thread to the pool.
but in the mean time, create a new Task/Bgw for a new job.
You may want to unsubscribe your Completed event from the old Bgw.
I think you should consider not cancelling the background worker.
If you cancel requests and the user types faster than your server returns queries, he will not see suggestions until he is finished typing.
In interactive scenarios like this, It could be better to show responses that run behind with what the user's typing. Your user will know he can stop typing if the word he has in mind is your suggestions list.
This will be also better for your server when it is busy, because instead of many cancelled requests, who will cost something but that are ultimately not shown, there will be fewer requests whose response you actually use.
I ran into similar issues with (3d) rendering applications, where the beginner's mistake is to cancel and rerender on every mousemove. This lead to a lot of computation and little interactive feedback.

Display progress bar while doing some work in C#?

I want to display a progress bar while doing some work, but that would hang the UI and the progress bar won't update.
I have a WinForm ProgressForm with a ProgressBar that will continue indefinitely in a marquee fashion.
using(ProgressForm p = new ProgressForm(this))
{
//Do Some Work
}
Now there are many ways to solve the issue, like using BeginInvoke, wait for the task to complete and call EndInvoke. Or using the BackgroundWorker or Threads.
I am having some issues with the EndInvoke, though that's not the question. The question is which is the best and the simplest way you use to handle such situations, where you have to show the user that the program is working and not unresponsive, and how do you handle that with simplest code possible that is efficient and won't leak, and can update the GUI.
Like BackgroundWorker needs to have multiple functions, declare member variables, etc. Also you need to then hold a reference to the ProgressBar Form and dispose of it.
Edit: 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, but I need to keep call the Application.DoEvents(); for the progress bar to keep rotating.
The bounty is for the best code solution for this problem. I just need to call Application.DoEvents() so that the Marque progress bar will work, while the worker function works in the Main thread, and it doesn't return any progress notification. I never needed .NET magic code to report progress automatically, I just needed a better solution than :
Action<String, String> exec = DoSomethingLongAndNotReturnAnyNotification;
IAsyncResult result = exec.BeginInvoke(path, parameters, null, null);
while (!result.IsCompleted)
{
Application.DoEvents();
}
exec.EndInvoke(result);
that keeps the progress bar alive (means not freezing but refreshes the marque)
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).
For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls
There's a load of information about threading with .NET/C# on Stackoverflow, but the article that cleared up windows forms threading for me was our resident oracle, Jon Skeet's "Threading in Windows Forms".
The whole series is worth reading to brush up on your knowledge or learn from scratch.
I'm impatient, just show me some code
As far as "show me the code" goes, below is how I would do it with C# 3.5. The form contains 4 controls:
a textbox
a progressbar
2 buttons: "buttonLongTask" and "buttonAnother"
buttonAnother is there purely to demonstrate that the UI isn't blocked while the count-to-100 task is running.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonLongTask_Click(object sender, EventArgs e)
{
Thread thread = new Thread(LongTask);
thread.IsBackground = true;
thread.Start();
}
private void buttonAnother_Click(object sender, EventArgs e)
{
textBox1.Text = "Have you seen this?";
}
private void LongTask()
{
for (int i = 0; i < 100; i++)
{
Update1(i);
Thread.Sleep(500);
}
}
public void Update1(int i)
{
if (InvokeRequired)
{
this.BeginInvoke(new Action<int>(Update1), new object[] { i });
return;
}
progressBar1.Value = i;
}
}
And another example that BackgroundWorker is the right way to do it...
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace SerialSample
{
public partial class Form1 : Form
{
private BackgroundWorker _BackgroundWorker;
private Random _Random;
public Form1()
{
InitializeComponent();
_ProgressBar.Style = ProgressBarStyle.Marquee;
_ProgressBar.Visible = false;
_Random = new Random();
InitializeBackgroundWorker();
}
private void InitializeBackgroundWorker()
{
_BackgroundWorker = new BackgroundWorker();
_BackgroundWorker.WorkerReportsProgress = true;
_BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
_BackgroundWorker.ProgressChanged += (sender, e) =>
{
_ProgressBar.Style = ProgressBarStyle.Continuous;
_ProgressBar.Value = e.ProgressPercentage;
};
_BackgroundWorker.RunWorkerCompleted += (sender, e) =>
{
if (_ProgressBar.Style == ProgressBarStyle.Marquee)
{
_ProgressBar.Visible = false;
}
};
}
private void buttonStart_Click(object sender, EventArgs e)
{
_BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
{
_ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(10);
_BackgroundWorker.ReportProgress(i / 10);
}
}));
}
}
}
Indeed you are on the right track. You should use another thread, and you have identified the best ways to do that. The rest is just updating the progress bar. In case you don't want to use BackgroundWorker like others have suggested, there is one trick to keep in mind. The trick is that you cannot update the progress bar from the worker thread because UI can be only manipulated from the UI thread. So you use the Invoke method. It goes something like this (fix the syntax errors yourself, I'm just writing a quick example):
class MyForm: Form
{
private void delegate UpdateDelegate(int Progress);
private void UpdateProgress(int Progress)
{
if ( this.InvokeRequired )
this.Invoke((UpdateDelegate)UpdateProgress, Progress);
else
this.MyProgressBar.Progress = Progress;
}
}
The InvokeRequired property will return true on every thread except the one that owns the form. The Invoke method will call the method on the UI thread, and will block until it completes. If you don't want to block, you can call BeginInvoke instead.
BackgroundWorker is not the answer because it may be that I don't get the progress notification...
What on earth does the fact that you're not getting progress notification have to do with the use of BackgroundWorker? If your long-running task doesn't have a reliable mechanism for reporting its progress, there's no way to reliably report its progress.
The simplest possible way to report progress of a long-running method is to run the method on the UI thread and have it report progress by updating the progress bar and then calling Application.DoEvents(). This will, technically, work. But the UI will be unresponsive between calls to Application.DoEvents(). This is the quick and dirty solution, and as Steve McConnell observes, the problem with quick and dirty solutions is that the bitterness of the dirty remains long after the sweetness of the quick is forgotten.
The next simplest way, as alluded to by another poster, is to implement a modal form that uses a BackgroundWorker to execute the long-running method. This provides a generally better user experience, and it frees you from having to solve the potentially complicated problem of what parts of your UI to leave functional while the long-running task is executing - while the modal form is open, none of the rest of your UI will respond to user actions. This is the quick and clean solution.
But it's still pretty user-hostile. It still locks up the UI while the long-running task is executing; it just does it in a pretty way. To make a user-friendly solution, you need to execute the task on another thread. The easiest way to do that is with a BackgroundWorker.
This approach opens the door to a lot of problems. It won't "leak," whatever that is supposed to mean. But whatever the long-running method is doing, it now has to do it in complete isolation from the pieces of the UI that remain enabled while it's running. And by complete, I mean complete. If the user can click anywhere with a mouse and cause some update to be made to some object that your long-running method ever looks at, you'll have problems. Any object that your long-running method uses which can raise an event is a potential road to misery.
It's that, and not getting BackgroundWorker to work properly, that's going to be the source of all of the pain.
I have to throw the simplest answer out there. You could always just implement the progress bar and have no relationship to anything of actual progress. Just start filling the bar say 1% a second, or 10% a second whatever seems similar to your action and if it fills over to start again.
This will atleast give the user the appearance of processing and make them understand to wait instead of just clicking a button and seeing nothing happen then clicking it more.
Here is another sample code to use BackgroundWorker to update ProgressBar, just add BackgroundWorker and Progressbar to your main form and use below code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Shown += new EventHandler(Form1_Shown);
// To report progress from the background worker we need to set this property
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}
refrence:from codeproject
Use the BackgroundWorker component it is designed for exactly this scenario.
You can hook into its progress update events and update your progress bar. The BackgroundWorker class ensures the callbacks are marshalled to the UI thread so you don't need to worry about any of that detail either.
Reading your requirements the simplest way would be to display a mode-less form and use a standard System.Windows.Forms timer to update the progress on the mode-less form. No threads, no possible memory leaks.
As this only uses the one UI thread, you would also need to call Application.DoEvents() at certain points during your main processing to guarantee the progress bar is updated visually.
Re: Your edit.
You need a BackgroundWorker or Thread to do the work, but it must call ReportProgress() periodically to tell the UI thread what it is doing. DotNet can't magically work out how much of the work you have done, so you have to tell it (a) what the maximum progress amount you will reach is, and then (b) about 100 or so times during the process, tell it which amount you are up to. (If you report progress fewer than 100 times, the progess bar will jump in large steps. If you report more than 100 times, you will just be wasting time trying to report a finer detail than the progress bar will helpfully display)
If your UI thread can happily continue while the background worker is running, then your work is done.
However, realistically, in most situations where the progress indication needs to be running, your UI needs to be very careful to avoid a re-entrant call. e.g. If you are running a progress display while exporting data, you don't want to allow the user to start exporting data again while the export is in progress.
You can handle this in two ways:
The export operation checks to see if the background worker is running, and disabled the export option while it is already importing. This will allow the user to do anything at all in your program except exporting - this could still be dangerous if the user could (for example) edit the data that is being exported.
Run the progress bar as a "modal" display so that your program reamins "alive" during the export, but the user can't actually do anything (other than cancel) until the export completes. DotNet is rubbish at supporting this, even though it's the most common approach. In this case, you need to put the UI thread into a busy wait loop where it calls Application.DoEvents() to keep message handling running (so the progress bar will work), but you need to add a MessageFilter that only allows your application to respond to "safe" events (e.g. it would allow Paint events so your application windows continue to redraw, but it would filter out mouse and keyboard messages so that the user can't actually do anything in the proigram while the export is in progress. There are also a couple of sneaky messages you'll need to pass through to allow the window to work as normal, and figuring these out will take a few minutes - I have a list of them at work, but don't have them to hand here I'm afraid. It's all the obvious ones like NCHITTEST plus a sneaky .net one (evilly in the WM_USER range) which is vital to get this working).
The last "gotcha" with the awful dotNet progress bar is that when you finish your operation and close the progress bar you'll find that it usually exits when reporting a value like "80%". Even if you force it to 100% and then wait for about half a second, it still may not reach 100%. Arrrgh! The solution is to set the progress to 100%, then to 99%, and then back to 100% - when the progress bar is told to move forwards, it animates slowly towards the target value. But if you tell it to go "backwards", it jumps immediately to that position. So by reversing it momentarily at the end, you can get it to actually show the value you asked it to show.
If you want a "rotating" progress bar, why not set the progress bar style to "Marquee" and using a BackgroundWorker to keep the UI responsive? You won't achieve a rotating progress bar easier than using the "Marquee" - style...
We are use modal form with BackgroundWorker for such a thing.
Here is quick solution:
public class ProgressWorker<TArgument> : BackgroundWorker where TArgument : class
{
public Action<TArgument> Action { get; set; }
protected override void OnDoWork(DoWorkEventArgs e)
{
if (Action!=null)
{
Action(e.Argument as TArgument);
}
}
}
public sealed partial class ProgressDlg<TArgument> : Form where TArgument : class
{
private readonly Action<TArgument> action;
public Exception Error { get; set; }
public ProgressDlg(Action<TArgument> action)
{
if (action == null) throw new ArgumentNullException("action");
this.action = action;
//InitializeComponent();
//MaximumSize = Size;
MaximizeBox = false;
Closing += new System.ComponentModel.CancelEventHandler(ProgressDlg_Closing);
}
public string NotificationText
{
set
{
if (value!=null)
{
Invoke(new Action<string>(s => Text = value));
}
}
}
void ProgressDlg_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
FormClosingEventArgs args = (FormClosingEventArgs)e;
if (args.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
}
}
private void ProgressDlg_Load(object sender, EventArgs e)
{
}
public void RunWorker(TArgument argument)
{
System.Windows.Forms.Application.DoEvents();
using (var worker = new ProgressWorker<TArgument> {Action = action})
{
worker.RunWorkerAsync();
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
ShowDialog();
}
}
void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Error = e.Error;
DialogResult = DialogResult.Abort;
return;
}
DialogResult = DialogResult.OK;
}
}
And how we use it:
var dlg = new ProgressDlg<string>(obj =>
{
//DoWork()
Thread.Sleep(10000);
MessageBox.Show("Background task completed "obj);
});
dlg.RunWorker("SampleValue");
if (dlg.Error != null)
{
MessageBox.Show(dlg.Error.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dlg.Dispose();

Categories