【发布时间】:2020-06-23 13:47:01
【问题描述】:
我是异步编程的新手。 我的 UI 中有一个按钮和文本框。我想单击该按钮,然后它将使用 FileStream.ReadAsync 方法读取文件,然后它应该在文本框中显示文件的结果。 问题是我不想在读取文件时阻止我的 UI。 我认为使用 Read 方法应该这样做。但它不起作用。此方法有什么不正确之处以及如何将 Read 更改为 ReadAsync?
private void Button_Click(object sender, RoutedEventArgs e)
{
string filename = @"D:\Log\log.txt";
byte[] result;
UnicodeEncoding uniencoding = new UnicodeEncoding();
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
result = new byte[SourceStream.Length];
Task<int> tf = new Task<int>(()=> SourceStream.Read(result, 0, (int)SourceStream.Length));
tf.ContinueWith((x) =>
{
try
{
string txt = Encoding.ASCII.GetString(result);
Dispatcher.BeginInvoke((Action)(() => txtBox.Text = txt));
}
catch (Exception ae)
{
MessageBox.Show(ae.Message);
}
});
tf.Start();
}
【问题讨论】:
标签: c# asynchronous async-await task task-parallel-library