WPF richtextbox异步显示长文本

HFMS_PrPrPr 2016-11-25 11:00:39
读取一个文本文档显示在richtextbox里
下面是代码


这样子运行的时候还是会卡住UI线程

...全文
294 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
HFMS_PrPrPr 2016-11-27
  • 打赏
  • 举报
回复
引用 3 楼 xinweilee 的回复:
private void Button_Click(object sender, RoutedEventArgs e) { var doc = new FlowDocument(); Paragraph graph = new Paragraph(); doc.Blocks.Add(graph); textbox.Document = doc; Action action = new Action(() => { ReadText(graph); }); action.BeginInvoke(null, null); } /// <summary> /// Reads the text. /// </summary> /// <param name="info">The info.</param> /// <returns></returns> private static void ReadText(Paragraph graph) { try { using (FileStream stream = new FileStream(@"D:\oo\test.txt", FileMode.Open)) { using (StreamReader reader = new StreamReader(stream, Encoding.Default)) { while (!reader.EndOfStream) { var content = reader.ReadLine(); if (!string.IsNullOrEmpty(content)) { graph.Dispatcher.Invoke(() => { graph.Inlines.Add(content); graph.Inlines.Add(Environment.NewLine); }); } System.Threading.Thread.Sleep(5); } } } } catch { } } 大概试了一下,思想就是将耗时UI拆分成很多个,然后异步执行,过程中给cpu空闲时间,避免ui假死,具体例子的控件是否合适,看你的需求了
方法可行,感谢
xinweilee 2016-11-25
  • 打赏
  • 举报
回复
因为你一下子将所有文本显示到textbox,所有在这个显示过程中可能会卡住ui,这样试一下 while(!stream.EndOfStream) { var strline = reader.ReadLine(); threadricktextbox(strline);//方法里需要调整成追加方式 Thread.Sleep(1); }
xinweilee 2016-11-25
  • 打赏
  • 举报
回复
private void Button_Click(object sender, RoutedEventArgs e) { var doc = new FlowDocument(); Paragraph graph = new Paragraph(); doc.Blocks.Add(graph); textbox.Document = doc; Action action = new Action(() => { ReadText(graph); }); action.BeginInvoke(null, null); } /// <summary> /// Reads the text. /// </summary> /// <param name="info">The info.</param> /// <returns></returns> private static void ReadText(Paragraph graph) { try { using (FileStream stream = new FileStream(@"D:\oo\test.txt", FileMode.Open)) { using (StreamReader reader = new StreamReader(stream, Encoding.Default)) { while (!reader.EndOfStream) { var content = reader.ReadLine(); if (!string.IsNullOrEmpty(content)) { graph.Dispatcher.Invoke(() => { graph.Inlines.Add(content); graph.Inlines.Add(Environment.NewLine); }); } System.Threading.Thread.Sleep(5); } } } } catch { } } 大概试了一下,思想就是将耗时UI拆分成很多个,然后异步执行,过程中给cpu空闲时间,避免ui假死,具体例子的控件是否合适,看你的需求了
HFMS_PrPrPr 2016-11-25
  • 打赏
  • 举报
回复
引用 1 楼 xinweilee 的回复:
因为你一下子将所有文本显示到textbox,所有在这个显示过程中可能会卡住ui,这样试一下 while(!stream.EndOfStream) { var strline = reader.ReadLine(); threadricktextbox(strline);//方法里需要调整成追加方式 Thread.Sleep(1); }
确实是所有文本显示到richtextbox上的时候卡住的,但是这样子写也还是不行,还是会卡到添加完才能动

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧