I was writing this application for a client of mine, and I needed to dsiplay a "Please Wait..." message while disabling access to the the rest of the application controls during a lengthy background process, but at the same time, wanted to show that the application is alive and well.... not frozen, maybe even put a cancel or a stop button to terminate the lengthy process.
One way to implement this in C# is to show a modal dialog while the lengthy process is being started on a separate background thread.
The question is how to make the thread notify the dialog when it finishes processing so that the dialog can close automatically.
Here is the code to achieve this in the main thread:
private
void
btnRunALengthyProcess_Click(
object
sender,
EventArgs
e)
{
// Start my lengthy Process
Thread lengthyProcessThread =
new
Thread(
new
ThreadStart
(RunLengthyProcess));
lengthyProcessThread.IsBackground =
true
;
// so not to have stray running threads if the main
//form is closed
lengthyProcessThread.Start();
// Display the Please Wait Dialog here
_pleaseWaitDlg =
new
PleaseWaitDlg();
_pleaseWaitDlg.ShowDialog();
}
void
RunLengthyProcess()
{
// Do something that takes a long time
// (sleep for 10 seconds)
Thread.Sleep(10000);
// Request the dialog to close itself
_pleaseWaitDlg.ShouldCloseNow =
true
;
}
And now, we need to implement PleaseWaitDlg. Here is how you can implement one:
public
volatile
bool
ShouldCloseNow;
private
void
PleaseWaitDlg_Load(
object
sender,
EventArgs
e)
{
ShouldCloseNow =
false
;
// Start the timer to check when to close the dialog
tmrCheckIfNeedToCloseDialog.Start();
}
private
void
tmrCheckIfNeedToCloseDialog_Tick(
object
sender,
EventArgs
e)
{
if
(ShouldCloseNow)
Close();
}
Notice how the background thread makes use of the volatile boolean to notify the main thread that it's time to close the "Please Wait" dialog.
You should make sure you control the GUI Only from the main thread... this is a .NET restriction, hence, the use of the volatile variable.
Source: http://www.mycsharpcorner.com/
Hope this helps, Here is the link to the full source:
Source Code