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假死,具体例子的控件是否合适,看你的需求了
因为你一下子将所有文本显示到textbox,所有在这个显示过程中可能会卡住ui,这样试一下 while(!stream.EndOfStream) { var strline = reader.ReadLine(); threadricktextbox(strline);//方法里需要调整成追加方式 Thread.Sleep(1); }
110,546
社区成员
642,581
社区内容
加载中
让您成为最强悍的C#开发者
试试用AI创作助手写篇文章吧