我试图实现一个ProgressBar
,它将在文件传输过程中显示。
文件传输使用BackgroundWorker
完成。
只是检查我尝试从主线程取得进展的功能,但没有任何反应。
代码:
myProgressBar.Minimum = 0;
myProgressBar.Maximum = numOfPackets;
这是后台工作人员代码......
然后:
myProgressBar.IsEnabled = true;
for (int i = 0; i < buff.Length; i++)
{
myProgressBar.Value = i;
myProgressBar.UpdateDefaultStyle();
}
为什么没有变化?
答案 0 :(得分:0)
对于wpf,您可以使用:
this.Dispacher.BeginInvoke(new Action(()=> { for(int i...)...; }));
答案 1 :(得分:0)
在后台线程上进行IO或文件传输是非常糟糕的,因为在文件传输或IO操作期间CPU没有被使用,所以你的后台线程没有做任何事情,只是等待IO进行comlpete而你浪费一个线程反过来导致内存的浪费。更多的缺点是你的UI将无法响应文件传输需要相当长的时间,即使你在后台线程上做。
我可以继续编写在后台线程上执行IO工作的缺点,但是你应该在.Net中请求一个关于异步执行IO的文档。 后台线程用于CPU密集型工作,例如涉及CPU的一些繁重计算。
您应该使用异步IO。使用async和await。请阅读有关异步IO的信息。 我有一个示例,说明您正在使用带有进度条和响应式UI的纯异步IO。我明天会写的。
** 下面是asynchronus io文件传输代码,假设所有文件的进度更新大小相同 下面提到的代码将起作用,即使在文件被转换时移动窗口,应用程序也不会挂起。 **
<强> MainWindow.xaml 强>
<Window x:Class="asyncawait.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="514" Width="674">
<Grid Margin="0,0,0,4">
<ScrollViewer Name="scrv_Log" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Width="397" Margin="33,61,0,67">
<ListBox VirtualizingPanel.VirtualizationMode="Recycling" ItemsSource="{Binding Datas,Mode=OneWay}" Background="White" Foreground="Red"/>
</ScrollViewer>
<TextBlock Height="40" Width="70" FontSize="10" Foreground="Green" Text="{Binding FileCounter,Mode=OneWay}" Margin="540,281,56,158"></TextBlock>
<Button Foreground="Black" IsEnabled="{Binding IsButtonEnabled}" Click="Button_Click" Height="40" Width="40" RenderTransformOrigin="4.65,0.425" Margin="540,210,86,229"></Button>
<ProgressBar Value="{Binding Progressvalue,Mode=OneWay}" Name="prg" Foreground="Green" Height="20" Width="600" Margin="23,453,44.2,7"></ProgressBar>
<Label Content="{Binding ElementName=prg,Path=Value}" ContentStringFormat="{}{0}%" Height="25" Margin="253,0,295.2,22" VerticalContentAlignment="Center" VerticalAlignment="Bottom"/>
<TextBox Background='AliceBlue' HorizontalAlignment="Left" Height="23" Margin="525,109,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="97"/>
</Grid>
</Window>
****这里的代码背后有异步IO **
public partial class MainWindow: Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
public double Progressvalue
{
get
{
return _Progressvalue;
}
set
{
if(value!=_Progressvalue)
{
_Progressvalue=value;
OnPropertyChanged();
}
}
}
private Double _Progressvalue=0;
private bool _IsEnabled=true;
public Boolean IsButtonEnabled {
get
{
return _IsEnabled;
}
set
{
if(value!=_IsEnabled)
{
_IsEnabled = value;
OnPropertyChanged();
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
IsButtonEnabled = false;
await AsyncTransferFiles();
IsButtonEnabled = true;
scrv_Log.ScrollToBottom();
}
private String fileCounter;
public String FileCounter
{
get
{ return fileCounter; }
set
{
if (value != fileCounter)
{
fileCounter = value;
OnPropertyChanged();
}
}
}
private ObservableCollection<String> _Datas = new ObservableCollection<string>();
public ObservableCollection<String> Datas
{
get
{
return _Datas;
}
}
private async Task AsyncTransferFiles()
{
var fileNames = Directory.GetFiles("C:\\Data1").ToList();
int totalCount = fileNames.Count;
pr = (double)1 / totalCount;
int counter = 0;
var progress = new Progress<double>();
progress.ProgressChanged += (sender, e) =>
{
Progressvalue = Double.Parse(e.ToString());
};
foreach (var fileName in fileNames)
{
await (CopyFileAsync(fileName, "C:\\GradebookTemp1\\" + fileName.Split('\\')[2], progress, ++counter));
}
}
double pr = 0.0;
public async Task CopyFileAsync(string sourcePath, string destinationPath,IProgress<double> progress ,int fileCounter)
{
using (Stream source = File.Open(sourcePath,FileMode.Open))
{
using (Stream destination = File.Create(destinationPath))
{
await source.CopyToAsync(destination);
progress.Report((int)(pr*fileCounter*100));
FileCounter = fileCounter.ToString();
Datas.Add("Copied File: " + sourcePath);
scrv_Log.ScrollToBottom();
}
}
}
private void EnableButton()
{
IsButtonEnabled = true;
}
private void OnPropertyChanged([CallerMemberName] String propertyName=null)
{
var handler = PropertyChanged;
if(null!=handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
答案 2 :(得分:0)
该解决方案适用于我:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 100; i++)
{
progBar.Value = i;
progBar.Refresh();
Thread.Sleep(10);
}
}
}
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate () { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}
}
我的关联示例-XAML基本上包含:
<Grid>
<ProgressBar x:Name="progBar" HorizontalAlignment="Left" Height="10" Margin="116,175,0,0" VerticalAlignment="Top" Width="100"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="156,51,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>
但是我觉得这对理解来说甚至都没有必要 - 我认为你得到了代码的重点,它是非常自我描述的
答案 3 :(得分:0)
只需Refresh控件:
myProgressBar.Refresh();