我有一个C#WPF桌面应用程序。
我想做'某些'工作',当我这样做时,我想在等待完成时显示进度条/信息。
所以,为了模仿这个,我有这个UI:
<Window xmlns:mui="http://firstfloorsoftware.com/ModernUI" x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel x:Name="frm" Orientation="Horizontal" >
<Button Click="Button_Click" Content="Press Me!" />
<Label Content="this is my test stuff"></Label>
</StackPanel>
<TextBox Text="Hello Andy" x:Name="prog" Visibility="Collapsed"></TextBox>
</Grid>
</Window>
我的守则背后:
public MainWindow()
{
InitializeComponent();
}
private void ShowBusy()
{
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() =>
{
frm.Visibility = Visibility.Collapsed;
prog.Visibility = Visibility.Visible;
}));
}
private void HideBusy()
{
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
new Action(() =>
{
frm.Visibility = System.Windows.Visibility.Visible;
prog.Visibility = System.Windows.Visibility.Collapsed;
}));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(ShowBusy);
th.Start();
while (true)
{
System.Threading.Thread.Sleep(100);
}
HideBusy();
}
当我运行时,没有显示'Hello Andy'并且无限循环正在运行..
答案 0 :(得分:2)
private void Button_Click(object sender, RoutedEventArgs e)
{
Thread th = new Thread(DoSomething);
th.Start();
}
private void DoSomething()
{
ShowBusy();
while (true) // No Exit Clause ???
{
System.Threading.Thread.Sleep(100);
}
HideBusy();
}
答案 1 :(得分:1)
异步任务有IProgress<T>
,可让您了解长时间运行方法的进度。
private async void Button_Click(object sender, RoutedEventArgs e)
{
IProgress<int> progress = new Progress<int>();
progress.ProgressChanged += progress_ProgressChanged;
await DoSomething(progress);
}
private void progress_ProgressChanged(object sender, int e)
{
if(e < 100)
{
ShowBusy(e); //Show busy with progress percentage
}
else
{
HideBusy();
}
}
private async Task DoSomething(IProgress<int> progress)
{
progress.Report(0)
longMethod1();
progress.Report(50)
longMethod2();
progress.Report(100)
}