我正在尝试实现一个ProgressBar
将在文件传输过程中显示的内容。
文件传输是通过进行的BackgroundWorker
。
只是为了检查我尝试从主线程取得进展的功能,没有任何反应。
编码:
myProgressBar.Minimum = 0;
myProgressBar.Maximum = numOfPackets;
这是后台工作人员代码...
然后:
myProgressBar.IsEnabled = true;
for (int i = 0; i < buff.Length; i++)
{
myProgressBar.Value = i;
myProgressBar.UpdateDefaultStyle();
}
为什么什么都没有改变?
在后台线程上进行IO或文件传输是非常糟糕的,因为在文件传输或IO操作期间,CPU没有被使用,因此您的后台线程没有做任何事情,而是在等待IO竞争,并且您浪费了一个线程,这反过来又导致浪费另一个缺点是,即使您在后台线程上进行操作,UI也将无法响应文件传输,而这需要花费大量时间。
我可以继续编写在后台线程上进行IO工作的缺点,但是您应该索取一份有关在.Net中异步进行IO的文档。后台线程用于CPU密集型工作,例如涉及CPU的大量计算。
您应该使用异步IO。使用异步并等待。请阅读有关异步IO的信息。我有一个示例示例,说明您如何使用带有进度栏和响应式UI的纯异步IO进行操作。我明天再写。
**下面是异步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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句