我试图显示一个从另一个源获取数据的繁忙指示器。
工作流程
进程starting
样本代码
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;
}当dispatcher循环正在进行时,繁忙指示符不会启动,该指示符只在循环之后才开始。在上述情况下,指示符不显示,但如果IsBusy标志未设置为假指示符,则在循环结束后启动。
我不知道我做错了什么还是逻辑不正确?请帮我解决这个问题。
发布于 2020-11-17 14:33:55
您似乎要在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;https://stackoverflow.com/questions/64877138
复制相似问题