我从文件中读取行,每行显示在文本框中。我使用事件但app停止并等待加载所有行。显示所有行后。这是代码: public partial class MainWindow:Window { FileReader reader = new FileReader(); public MainWindow() { 的InitializeComponent(); reader.OnReadLine + =消息; }
private void Message(object sender, LineEventArgs e)
{
Dispatcher.Invoke((Action)(() =>
{
textBox.Text += e.Content + "\n";
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}));
}
private void button_Click(object sender, RoutedEventArgs e)
{
TaskFactory taskFactory = new TaskFactory();
var x = taskFactory.StartNew(() => reader.Read());
Task.WaitAll(x);
}
}
class LineEventArgs : EventArgs
{
public string Content { get; }
public LineEventArgs(string content)
{
Content = content;
}
}
delegate void OnReadLineHandler(object sender, LineEventArgs e);
class FileReader
{
public event OnReadLineHandler OnReadLine;
public void Read()
{
var fileStream = new FileStream("text.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
while (!streamReader.EndOfStream)
{
OnRead(streamReader.ReadLine());
}
}
}
private void OnRead(string text)
{
if (OnReadLine != null)
OnReadLine(this, new LineEventArgs(text));
}
}
感谢您的建议
答案 0 :(得分:1)
你告诉用户界面要等待读取整个文件,因为你说的是Task.WaitAll(x)
含义,你说,“等到这个完成了。”而是使用等待如下。
private async void button_Click(object sender, RoutedEventArgs e)
{
TaskFactory taskFactory = new TaskFactory();
var x = taskFactory.StartNew(() => reader.Read());
await x;
}
注意我也可以通过将private void button_Click(object sender, RoutedEventArgs e)
更改为private async void button_Click(object sender, RoutedEventArgs e)
尝试一下,看看是否有帮助。