Vynz
Vynz

Reputation: 83

Set a WPF Mahapps Progress Dialog

I'm trying to replace my ProgressBar to a Progress Dialog using Mahapps.

So I started writing this:

private void btnClick(object sender, RoutedEventArgs e)
{ 
    ConfRelais();
}

public async void ConfRelais()
{
    var controller = await this.ShowProgressAsync("hey", "hoy");
    controller.Maximum = 128;
    while (flag == 0)
    {
        string data = RelayBoard_Port.ReadTo("\r\n");
        if (data == "ok") { controller.SetMessage("Done Process");
                            flag = 1; }
        else { controller.SetProgress(Int32.Parse(data)); }
    }
    await controller.CloseAsync();
}

But the progress dialog only displays when it's over.. As I'm still a beginner in c# maybe I'm missing some importants points to setup that kind of function.

Upvotes: 2

Views: 1074

Answers (1)

mm8
mm8

Reputation: 169200

You should execute the loop on a background thread:

public async void ConfRelais()
{
    var controller = await this.ShowProgressAsync("hey", "hoy");
    controller.Maximum = 128;
    await Task.Run(() =>
    {
        while (flag == 0)
        {
            string data = RelayBoard_Port.ReadTo("\r\n");
            if (data == "ok")
            {
                controller.SetMessage("Done Process");
                flag = 1;
            }
            else { controller.SetProgress(Int32.Parse(data)); }
        }
    });
    await controller.CloseAsync();
}

A single thread cannot both update the UI and execute your loop simultaneously.

You also don't really need a flag. You could just break out of the loop when you receive "ok":

while (true)
{
    string data = RelayBoard_Port.ReadTo("\r\n");
    if (data == "ok")
    {
        controller.SetMessage("Done Process");
        break;
    }
    else { controller.SetProgress(Int32.Parse(data)); }
}

Upvotes: 3

Related Questions