BusyIndi​​cator 动画停止并延迟操作

BusyIndicator animation stops with delayed operation

我正在尝试显示一个关于从其他来源获取数据的忙碌指示器。

工作流程

  1. 繁忙指示器在进程启动时启动
  2. 正在获取数据。
  3. 停止忙碌指示器。

示例代码

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;
        }

忙碌指示器在调度程序循环进行时不启动,指示器仅在循环后启动。在上述情况下,指示器未显示,但如果 IsBusy 标志未设置为 false,则指示器在循环后启动。

不知道是我做错了什么还是逻辑不对?请帮我解决这个问题。

您似乎在 GUI 线程上执行繁重的操作 - 这是因为 Dispatches.BeginInvoke 将操作分派给 GUI 线程。

可以更简单:

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;