Progress report : Need help understanding how it works - c#

I'm discovering this and can't get to understand how it works.
I have a progress bar in my main form and a menuStrip with a few maintenance functions on a mysql DB. I'd like to monitor progress for each of them.
So I have a class report and a Progress progress.
My declarations are as follow :
ProgressReportModel report = new ProgressReportModel();
Progress<ProgressReportModel> progress = new Progress<ProgressReportModel>();
progress.ProgressChanged += ReportProgress;
Now for each of the functions, I usually start with :
report.max = count;
report.visibility = true;
report.PercentageComplete = 0;
showtheProgress(progress);
with ShowtheProgress because I didn't find a way to convert from Progress to IProgress:
private void showtheProgress(IProgress<ProgressReportModel> progress)
{
progress.Report(report);
}
My issue is that this works for some functions but not all.
One difference that i can see if that it works with functions which are async but not with functions which are not async. To void flooding with code, just gonna put one function which is not working (ie the progressbar is not even showing up):
private void getMp3Files()
{
Globals.counttot = Directory.GetFiles(Globals.pathdir, "*.mp3", SearchOption.AllDirectories).Length;
report.max = Globals.counttot;
report.visibility = true;
report.PercentageComplete = x;
showtheProgress(progress);
DirectoryCopy(Globals.pathdir);
report.visibility = false;
report.PercentageComplete = 0;
showtheProgress(progress);
}
private void DirectoryCopy(string sourceDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles("*.mp3");
foreach (FileInfo file in files)
{
string temppath = Path.Combine(sourceDirName, file.Name);
Mp3 tmp_mp3 = Globals.getTags(temppath);
Globals.AddRowDs(tmp_mp3, false);
report.PercentageComplete = x; //not part of this code but it's a counter
showtheProgress(progress);
}
foreach (DirectoryInfo subdir in dirs) DirectoryCopy(subdir.FullName);
}
Thanks in advance!

It's not completely clear from the code that you have posted but my guess is that you have this problem because of the way how winforms works with threads and one of the reasons why the async was 'invented'.
A windows form is based on something like a message queue. Everything that you do on that form like moving your mouse, clicking a button, moving/resizing the form, typing and many more is converted to events and placed in this queue. In the background there is something constantly checking this queue for new events and executing them, one of these events is to draw the screen (paint), basically showing your form on the screen. You can only see the changes that are made (like showing a progress bar) during these paint events. If the time between these paint events is too long you see the message "Not responding".
Some of these events are also clicks on a button and these will execute all the code that you made. If the process of this event takes too long, then you will hold up the message queue and create the "Not responding" message. In order to avoid this, it's suggested to make these events as quick as possible, if you want to execute something that takes a long time, make it on another thread (see BackgroundWorker for an example). One downside of this is that it's not easy to communicate with the form (typically checking InvokeRequired and calling Invoke)
Here is where the async/await comes to help you. If you have a button click, and your code encounters an await that is not done yet, then it will add some code that, once the awaited method is done, it will add an event to the message queue to continue from this point in your code and end the event. This means that the rest of the events in the message queue (like showing that progress bar, displaying some text or handling other button clicks) are possible.
Just to be complete, some can suggest that you can sprinkle your code with Application.DoEvents(), these will force the message queue to be processed while you are still inside the method. This is a quick and dirty way that some people take without knowing the full implications of this. Know that it exists but avoid it.

Related

UI slightly freezes when update from background thread

I have a Winform with 4 PictureBox controls, each control will contain a diferent image. The process is:
An event x is raised, the eventargs from this event, contain the filenames of each image (4), an so on (file exists etc..). Then, I have to update the UI.
Commonly I use Invoke:
Invoke((ThreadStart)delegate()
{
picBig.Image = new Bitmap(strImageBig);
picLittle1.Image = new Bitmap(saLittle[0]);
picLittle2.Image = new Bitmap(saLittle[1]);
picLittle3.Image = new Bitmap(saLittle[2]);
});
// saLittle[] is a string array, contains, filenames: "image1.jpg"
But when this executes, the form freezes for a little time, about 500ms, I know it's a small interval but it's noticeable, then the app continues normally.
I was trying to find out the reason of that 'UI freeze', then, after research, I found BeginInvoke. Now my code looks like this:
BeginInvoke((MethodInvoker)delegate
{
picBig.Image = new Bitmap(strImageBig);
picLittle1.Image = new Bitmap(saLittle[0]);
picLittle2.Image = new Bitmap(saLittle[1]);
picLittle3.Image = new Bitmap(saLittle[2]);
});
This is a little faster. But the UI is still freezing for 200~300ms.
In the articles I've read, they say that BeginInvoke is a better way than Invoke.
The code is working OK, there is no problem with logic or anything else. I just want to know why this happens. I don't want to leave this doubt unclear. The project is already finished. Hope this be useful for someone else.
Maybe this is not the correct approach. I know there are many ways to update the UI from a background thread, but is there another way to make an update faster?
Or, do you think, the image loading is the reason? Is there another way to do a faster loading of images?
Thanks in advance.
This is because you're actually loading your images from disk on the UI thread along with setting the contents of the control. Calling the Bitmap constructor with a file path will go to the hard drive and load the image into memory.
Invoke and BeginInvoke will run the delegate that you provide on the thread that the control was created on, which is most likely going to be the UI thread.
...but is there another way to make an update faster?
Load the images on your background thread and, when they're actually loaded, invoke and set the images into the controls.
var big = new Bitmap(strImageBig);
var little1 = new Bitmap(saLittle[0]);
var little2 = new Bitmap(saLittle[1]);
var little3 = new Bitmap(saLittle[2]);
Invoke((ThreadStart)delegate()
{
picBig.Image = big;
picLittle1.Image = little1;
picLittle2.Image = little2;
picLittle3.Image = little3;
});
But when this executes, the form freezes for a little time, about 500ms, I know it's a small interval but it's noticeable, then the app continues normally.
Eventually, the UI thread needs to actually update the images. When the images are generated and updated on the UI thread, this will cause a (short) delay.

Using LocalMessageSender synchronously

We have an application that has a primary window, it can launch multiple other windows, in new browsers. We are using a silverlight application as a coordinating server in the primary window to close all windows that are part of the app, regardless of the way they are opened (we can't guarantee it was via window.open so don't always have a handle to the window in javascript).
On log out, we want to signal all the other windows to perform an auto-save, if necessary, then close down.
So all windows have a silverlight app, they coordinate using localmessagesenders. However, these are asynchronous:
private void ProcessAutosave()
{
foreach (string s in _windows)
{
SendMessage(s, "notify-logout");
}
// code here quoted later...
}
// sendasynch doesn't send until the method terminates, so have to do it in it's own function.
private void SendMessage(string to, string message)
{
var lms = new LocalMessageSender(to);
lms.SendCompleted += new EventHandler<SendCompletedEventArgs>(SenderSendCompleted);
lms.SendAsync(message);
}
Since the ProcessAutosave is called from a javascript onunload event which can't be cancelled, we need this to be synchronous and not complete before we have a response processed from each sub-window so the session state will still be valid etc.
In the SenderSendCompleted we remove items from _windows when they have said they're done.
So I added a loop on the end:
while(_windows.Count > 0) {
Thread.Sleep(1)
}
However, that never terminates, unless I put an iteration counter on it.
Am I the victim of a compiler optimisation meaning the changes in SenderSendCompleted do not affect that while loop, or, have I fundamentally misunderstood something? Or missed something obvious that's staring me in the face?
It sounds like a subtle verson of a race situation due to going sync/async. Couldn't the process in queston also receive notifications from the windows that they have received the message and are shutting down? Once all of the counter messages have been received, then the main app could shut down without the busy wait at the end(?).
I have found a way to work round. However, this does not really "solve" the problem generally, just in my case, which is also only supporting internet explorer.
function WindowCloseEventHandler()
{
var app = // get silverlight app handle...
app.doAutoSave();
var params = 'whatever you need';
var args = new Object();
args.hwnd = window;
window.showModalDialog('blocker.aspx',args,params);
}
function checkAutoSave()
{
var app = // get silverlight app handle...
return app.autosavecomplete();
}
Then in blocker.aspx we display a static "performing logout handlers" type message and do:
function timerTick()
{
if(window.dialogArguments.hwnd.checkAutoSave()) {
window.close();
} else {
setTimeout(timerTick, 500);
}
}
And start the timer on window load.
The child window's silverlight apps are notified to start an autosave, then they notify the parent when they are done. We then poll the parent's status from a modal dialog, which blocks the termination of the WindowCloseEventHandler() which we have wired up to the onclose event of the body.
It's hacky and horrible, but it means silverlight stays asynchronous and we're using a javascript timer so the javascript isn't loading the system.
Of course if the user closes the modal dialogue, there is a potential for issue.

How to monitor Textfile and continuously output content in a textbox?

I'm making a program that controls a game server. One of the functions I'm making, is a live server logfile monitor.
There is a logfile (a simple textfile) that gets updated by the server as it runs.
How do I continuously check the logfile and output it's content in a RichTextBox?
I did this simple function just try and get the content of the log. It will of course just get the text row by row and output it to my textbox. Also it will lock the program for as long as the loop runs, so I know it's useless.
public void ReadLog()
{
using (StreamReader reader = new StreamReader("server.log"))
{
String line;
// Read and display lines from the file until the end of the file is reached.
while ((line = reader.ReadLine()) != null)
{
monitorTextBox.AppendText(line + "\n");
CursorDown();
}
}
}
But how would you go about solving the live monitoring as simple as possible?
*** EDIT ***
I'm using Prescots solution. great stuff.
At the moment I'm using a sstreamreader to put the text from the file to my textbox. I ran into the problem is that, whenever I tried to access any of the gui controls in my event handler the program just stopped with no error or warnings.
I found out that it has to do with threading. I solved that like this:
private void OnChanged(object source, FileSystemEventArgs e)
{
if (monitorTextField.InvokeRequired)
{
monitorTextField.Invoke((MethodInvoker)delegate { OnChanged(source, e); });
}
else
{
StreamReader reader = new StreamReader("file.txt");
monitorTextField.Text = "";
monitorTextField.Text = reader.ReadToEnd();
reader.Close();
CursorDown();
}
}
Now my only problem is that the file.txt is used by the server so I can't access it, since it's "being used by another process". I can't control that process, so maybe I'm out of luck.
But the file can be opened in notepad while the server is running, so somehow it must be possible. Perhaps I can do a temp copy of the file when it updates and read the copy. I don't know.
Check out the System.IO.FileSystemWatcher class:
public static Watch()
{
var watch = new FileSystemWatcher();
watch.Path = #"D:\tmp";
watch.Filter = "file.txt";
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite; //more options
watch.Changed += new FileSystemEventHandler(OnChanged);
watch.EnableRaisingEvents = true;
}
/// Functions:
private static void OnChanged(object source, FileSystemEventArgs e)
{
if(e.FullPath == #"D:\tmp\file.txt")
{
// do stuff
}
}
Edit: if you know some details about the file, you could handle the most efficent way to get the last line. For example, maybe when you read the file, you can wipe out what you've read, so next time it's updated, you just grab whatever is there and output. Perhaps you know one line is added at a time, then your code can immediately jump to the last line of the file. Etc.
Although the FileSystemWatcher is the most simple solution I have found it to be unreliable in reality.. often a file can be updated with new contents but the FileSystemWatcher does not fire an event until seconds later and often never.
The only reliable way I have found to approach this is to check for changes to the file on a regular basis using a System.Timers.Timer object and checking the file size.
I have written a small class that demonstrates this available here:
https://gist.github.com/ant-fx/989dd86a1ace38a9ac58
Example Usage
var monitor = new LogFileMonitor("c:\temp\app.log", "\r\n");
monitor.OnLine += (s, e) =>
{
// WARNING.. this will be a different thread...
Console.WriteLine(e.Line);
};
monitor.Start();
The only real disadvantage here (apart from a slight performance delay caused by file size checking) is that because it uses a System.Timers.Timer the callback comes from a different thread.
If you are using a Windows Forms or WPF app you could easily modify the class to accept a SynchronizingObject which would ensure the event handler events are called from the same thread.
As #Prescott suggested, use a FileSystemWatcher. And make sure, you open the file with the appropriate FileShare mode (FileShare.ReadWrite seems to be appropriate), since the file might still be opened by the server. If you try to open the file exclusively while it is still used by another process, the open operation will fail.
Also in order to gain a bit of performance, you could remember the last position up to which you already have read the file and only read the new parts.
Use this answer on another post c# continuously read file.
This one is quite efficient, and it checks once per second if the file size has changed.
You can either run it on another thread (or convert to async code), but in any case you would need to marshall the text back to the main thread to append to the textbox.
Try adding a Timer and have the Timer.Tick set to an Interval of 1 second. On Timer.Tick you run the function.
private void myTimer_Tick(object sender, EventArgs e)
{
ReadLog();
}

C#: Periodically update GUI based on backgroundtask

I have a GUI that is for all intents and purposes really basic. A listview, an html form, and that's really it.
I want the user to have the following behavioral ability:
1 - Click a checkbox that says "Real-time". When clicked, a background thread will run once every 10 seconds.
2 - If there is a new file created (this is easy, to observe a new file) I want an alert displayed in my main gui. Where it is displayed for now is arbitrary (in a label, for example).
The main issue is I cannot figure out how to do this in a multi-threaded example. My goal is exactly in line with multithreading: do tasks 1 and 2, without locking task 1. Meaning, while the update check is running, the user can interact with the GUI as if nothing was going on in the background.
If you need more details to better answer this please let me know.
Thanks!
Here are a couple sites I found useful for implementing a background worker when I needed to perform database operations while still allowing the GUI to be responsive:
http://msdn.microsoft.com/en-us/library/zw97wx20.aspx
http://www.codeproject.com/KB/cs/AsynchronousCodeBlocks.aspx
Use events from the thread to tell the UI that something's changed:
// Just detected that that a new file has been created
if (this.FileCreated_Event != null)
{
this.FileCreate_Event(this, new FileEventArgs(newFileName));
}
where FileCreated_Event and FileEventArgs are declared appropriately.
Then in the UI when you receive the event you have the following:
this.fileChecker.FileCreated_Event += this.FileCreated_Event;
and:
private void FileCreated_Event(object sender, TrackStatusEventArgs e)
{
if ((sender as Control).InvokeRequired)
{
(sender as Control).Invoke(action);
}
else
{
action();
}
}
where action is the thing you want to do.
Try this tutorial. At the end I'm sure you'll be able to use threads. You must be careful though, because you'll have to manage those threads which can be a daunting task. I've never met a programmer who liked to debug multiple threads...

Animated Gif in form using C#

In my project, whenever a long process in being executed, a small form is displayed with a small animated gif file. I used this.Show() to open the form and this.Close() to close the form.
Following is the code that I use.
public partial class PlzWaitMessage : Form
{
public PlzWaitMessage()
{
InitializeComponent();
}
public void ShowSpalshSceen()
{
this.Show();
Application.DoEvents();
}
public void CloseSpalshScreen()
{
this.Close();
}
}
When the form opens, the image file do not immediately start animating. And when it does animate, the process is usually complete or very near completion which renders the animation useless. Is there a way I can have the gif animate as soon as I load the form?
Why not using threads? It's always good idea to learn something new.
You could simply put your "long process" in background thread, and use events to report to presentation layer, for example:
// in your "long process" class
public event Action<double> ReportCompletition;
// this method will start long process in separate background thread
public void Start()
{
Thread thread = new Thread(this.LongProcess);
thread.IsBackground = true;
thread.Start();
}
private void LongProcess()
{
// do something
// report 10% completition by raising event
this.ReportCompletition(0.1);
// do something more
this.ReportCompletition(0.5);
// ... and so on
}
This way, all you have to do is implement simple method in your Form/UI, which will consume this information.
public partial class MainApplicationWindow : Form
{
private LongProcessClass _longProcess;
public MainApplicationWindow
{
this.InitializeComponent();
this._longProcess = new LongProcessClass();
// bind UI updating method to long process class event
this._longProcess.ReportCompletition += this.DisplayCompletitionInfo;
}
private void DisplayCompletitionInfo(double completition)
{
// check if control you want to display info in needs to be invoked
// - request is coming from different thread
if (control.InvokeRequired)
{
Action<double> updateMethod = this.DisplayCompletitionInfo;
control.Invoke(updateMethod, new object[] { completition });
}
// here you put code to do actual UI updating,
// eg. displaying status message
else
{
int progress = (int) completition * 10;
control.Text = "Please wait. Long process progress: "
+ progress.ToString() + "%";
}
}
Of course, you can report anything you like from within long process. Be it completition rate, ready to display string messages, anything. You can also use events to report that long process has finished, broke, or any long process data you wish.
For more detailed information on this topic you might want to check MSDN tutorials on Threading and Events.
You should do the "long process" in a separate thread. I advice using the BackgroundWorker.
This will make your code more difficult though. One of the main reasons is, that you cannot communicate with the UI from the background thread.
Also note the warning from the linked page:
Caution
When using multithreading of
any sort, you potentially expose
yourself to very serious and complex
bugs. Consult the Managed Threading
Best Practices before implementing any
solution that uses multithreading.
If this is too difficult, you could call Application.DoEvents very frequent from your "long process" code.
Whatever you choose, this will make it possible for the user to interact with your form. For instance closing it. You should be aware of this.
Use the gif in a PictureBox, and have it open using Form pWait = new Form(); pWait.Show();

Categories