• 在后台线程中,从文件一行行异步加载内容进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#代码
    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;
                });
            }
    
  • 相关阅读:
    MySql 数据类型
    MySql 数据库的增删改
    MySql 联合查询
    Mysql 库的管理 --->>>>DDL
    MySql 子查询
    MySql 分页查询
    sql99语法的连接查询
    MySql 连接查询
    MySql 分组函数
    jQ处理页面中尺寸过大的图片
  • 原文地址:https://www.cnblogs.com/luna2333/p/15563301.html
Copyright © 2020-2023  润新知