BusyIndicator animation stops with delayed operation

298 views Asked by At

I'm trying to show a busy indicator on fetching data from another source.

Workflow

  1. Busy indicator starts on process starting
  2. Fetching data.
  3. Stop busy indicator.

Sample code

Xaml

 <busyIndicator:BusyIndicator x:Name="BusyIndicator" IsBusy="False" >
        <Grid>
            <Button x:Name="showindicator" Height="100" Width="200" Content="ShowIndicator" Grid.Row="1" Click="Showindicator_Click"/>
        </Grid>
    </busyIndicator:BusyIndicator>

C#

private async void Showindicator_Click(object sender, RoutedEventArgs e)
        {
            BusyIndicator.IsBusy = true;
            await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
            {
                // In my original code, fetching data here
                for (int i = 0; i < 5; i++)
                {
                    Console.WriteLine(i);
                    Thread.Sleep(1000);
                }
            }));
            BusyIndicator.IsBusy = false;
        }

Busy indicator doesn't start while dispatcher loop is in progress, the indicator starts only after the loop. In above case indicator not showing, but if IsBusy flag not set to false indicator starts after the loop.

I don't know Am I doing anything wrong or the logic not correct? Please help me to resolve this.

1

There are 1 answers

5
arconaut On BEST ANSWER

You seem to be performing your heavy operation on the GUI thread - this is because Dispatches.BeginInvoke dispatches the action to the GUI thread.

It can be easier:

BusyIndicator.IsBusy = true;
await Task.Run(() =>
{
    // this is now running in the background

    // In my original code, fetching data here
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(i);
        Thread.Sleep(1000); 

        Dispatcher.BeginInvoke(() => 
        {  
             // do UI stuff here
        });
    }
});

BusyIndicator.IsBusy = false;