I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process:
- Clicks button
- Method checks for updates, count is returned.
- If greater than 0, then ask the user if they want to install using MessageBox.Show().
- If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background.
- My update class has some events that are used to update a progress bar etc.
The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below).
- What should I do to make the messagebox disappear instantly before the update loop starts?
- Should I be using Threads instead of BeginInvoke()?
- Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread?
Code
// Button clicked event handler code...
DialogResult dlgRes = MessageBox.Show(
string.Format("There are {0} updates available.\n\nInstall these now?",
um2.Updates.Count), "Updates Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (dlgRes == DialogResult.Yes)
{
ProcessAllUpdates(um2);
}
// Processes a bunch of items in a loop
private void ProcessAllUpdates(UpdateManager2 um2)
{
for (int i = 0; i < um2.Updates.Count; i++)
{
Update2 update = um2.Updates[i];
ProcessSingleUpdate(update);
int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count);
UpdateOverallProgress(percentComplete);
}
}
// Process a single update with IAsyncResult
private void ProcessSingleUpdate(Update2 update)
{
update.Action.OnStart += Action_OnStart;
update.Action.OnProgress += Action_OnProgress;
update.Action.OnCompletion += Action_OnCompletion;
//synchronous
//update.Action.Run();
// async
IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); });
}
Screenshot