Click here to Skip to main content
16,016,345 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Kindly Explain it to me, i want to do some process while showing waiting progress bar but i am confused where and how to do it? Please let me know how the following code actually works, so that i could implement it.

i want to display a waiting message to the use unless the required process has been completed.

in the below code i have created two forms, the first form as some dummy data processing and the other form contains only a label and a progress bar. when i click the button on the first form the second from appears as a waiting dialogue box. its working properly but i just want to know how the below code is working so that i could modify it for my purpose.

What I have tried:

C#
public Form1()
        {
            InitializeComponent();
        }
        void SaveData()
        {
            for (int i = 0; i <= 5; i++)
            {
               // Thread.Sleep(500);// simulator
            }
            
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            using (Waitform objWaitForm = new Waitform(SaveData))
            {
                objWaitForm.ShowDialog(this);
            }
        }

//End From1///

 public Action Worker { get; set; }
        public Waitform(Action worker)
        {
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }

///End Waitform//
Posted
Updated 12-Sep-17 6:59am
v2
Comments
Richard MacCutchan 12-Sep-17 12:25pm    
And what was the result when you tried it? Also have you considered the ProgressBar Class (System.Windows.Forms)[^]?

1 solution

If you're looking at using Tasks for asynchronous operations, here is an example of how to do it.

1. Progress Form. Has a label to provide the progress messages - you can swap this out for a progress bar. Code-behind to handle the updates:
C#
public partial class ProgressForm: Form
{
    public ProgressForm()
    {
        InitializeComponent();
    }

    public void SetMessage(string text)
    {
        labMessage.Text = text;
    }
}

2. The calling form with the long running task:
C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        ShowProgressWindow();

        await UnitOfWork().ConfigureAwait(false);

        CloseProgressWindow();

    }

    private void CloseProgressWindow()
    {
        if (InvokeRequired)
        {
            Invoke((MethodInvoker)(CloseProgressWindow));
        }
        else
        {
            progress.Hide();
            button1.Enabled = true;
        }
    }

    private void ShowProgressWindow()
    {
        // disable button at start of process
        button1.Enabled = false;
        progress.Show(this);
    }

    private readonly ProgressForm progress = new ProgressForm();

    private readonly List<string> UpdateMessages = new List<string>
    {
        "Loading the fodder",
        "Watering the seeds",
        "Feeding the goats",
        "Clipping the flowers",
        "Smelling the roses",
        "Closing the doors",
        "Saving the changes",
        "Done!"
    };

    private Task<bool> UnitOfWork()
    {
        var tcs = new TaskCompletionSource<bool>();

        Task.Run(async () =>
        {
            for (int i = 0; i < 8; i++)
            {
                ProgressUpdate(UpdateMessages[i]);
                // Do long running synchronous work here...
                await Task.Delay(1000).ConfigureAwait(false); // simulate a 1 second task
            }

            // signal success!
            tcs.SetResult(true);

        }).ConfigureAwait(false);

        return tcs.Task;
    }

    private void ProgressUpdate(string updateMessage)
    {
        if (InvokeRequired)
            Invoke((MethodInvoker)(() => ProgressUpdate(updateMessage)));
        else
            progress.SetMessage(updateMessage);
    }
}
 
Share this answer
 
Comments
Member 13406242 13-Sep-17 11:57am    
Thanks very much let me try it
Graeme_Grant 13-Sep-17 13:06pm    
You are welcome. :)
Member 13406242 15-Sep-17 7:04am    
Dear valued! kindly dont mind one more thing to ask!

in the below code when i want to use any control of form1 (like txtName.text="abc"), it niether throws an exception nor gives some errors but the application becomes idle. but rather when i want some other process it works.


private Task<bool> UnitOfWork()
{
var tcs = new TaskCompletionSource<bool>();
try
{
Task.Run(async () =>
{
for (int i = 0; i < 8; i++)
{
ProgressUpdate(UpdateMessages[i]);

its the place, i am concerned with.

await Task.Delay(1000).ConfigureAwait(false); // simulate a 1 second task
}

// signal success!
tcs.SetResult(true);

}).ConfigureAwait(false);

return tcs.Task;
}
catch (Exception)
{
throw;

}

}
Graeme_Grant 15-Sep-17 7:08am    
Always make sure that you are updating UI controls on the UI thread. I do this in ?ProgressUpdate method.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900