I am new in asynchronous programming. I have a button and textbox in my UI. I want to click on the button and it will Read file using FileStream.ReadAsync method after that it should show the result of the file in the textbox. The problem is I don't want to block my UI while reading file. I thought that with Read method it should be done like this. But it does not work. What is incorrect in this method and how I can change Read to 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();
}