在后台线程中,从文件一行行异步加载内容进RichTextBox
XAML文件
XAML文件Code
<Grid>
<!--一个RichTextBox读取文件中的内容-->
<RichTextBox x:Name="LoadFileBox" Visibility="Collapsed"></RichTextBox>
<TextBlock x:Name="CountBox" Text="" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="60"/>
<TextBlock x:Name="TotalBox" HorizontalAlignment="Center" VerticalAlignment="Top" FontSize="30"/>
</Grid>
C#代码
public MainWindow()
{
InitializeComponent();
ComputeTotal();
Task.Factory.StartNew(() =>
{//开辟一个后台线程
LoadFileAsync();
});
}
/// <summary>
/// 计算总行数
/// </summary>
private void ComputeTotal()
{
int count = 0;
using (var fs = new FileStream(@"D:\work\记事本项目WPF\1.txt", FileMode.Open))
using (var reader = new StreamReader(fs))
{
while (reader.Peek() > 0)
{
string line = reader.ReadLine();//异步读
if (line != null)
{
count++;
}
}
TotalBox.Text = "总数:" + count;
}
}
/// <summary>
/// 异步加载文件内容到RichTextBox
/// </summary>
async void LoadFileAsync()
{
int count = 0;
using (var fs = new FileStream(@"D:\work\记事本项目WPF\1.txt", FileMode.Open))
using (var reader = new StreamReader(fs))
{
while (reader.Peek() > 0)
{
string line = await reader.ReadLineAsync();//异步读
if (line != null)
{
Dispatcher.Invoke(new Action(() =>
{
count++;
CountBox.Text = "当前解析到: " + count;
LoadFileBox.Document.Blocks.Add(new Paragraph(new Run(line)));
}));
}
}
}
Dispatcher.Invoke(() =>
{
CountBox.Visibility = Visibility.Collapsed;
TotalBox.Visibility = Visibility.Collapsed;
LoadFileBox.Visibility = Visibility.Visible;
});
}