You can't run a loop on and the update the UI on the same thread simultaneously. That's why you should always perform any long-running work on a background thread and update UI at regular intervals using the dispatcher.
The easiest way to run some code on a background thread is to use the task parallel library (TPL) to start a new task:
Task.Run(()=>
{
for (int i = 1; i <= 9999; i++)
{
System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds...
label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = 100 * i / 9999 + "%"));
}
});
my message box immediately show message after i run command while percentage is running
As mentioned the Task is being executed on another thread. So it will run in parallel with the UI thread. That's the reason why the UI can be updated while the loop is running.
You could use the Task.ContinueWith method to show the MessageBox after the task has completed:
int i = 1;
Task.Run(() =>
{
for (; i <= 9999; i++)
{
System.Threading.Thread.Sleep(1500); //simulate long-running operation by sleeping for 1.5s seconds...
label1.Dispatcher.BeginInvoke(new Action(() => label1.Content = (i / 9999) * 100 + "%"));
}
}).ContinueWith(t =>
{
MessageBox.Show("done..." + i.ToString());
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());