You don't want to be creating new Tasks
and managing them directly, it's better to call a method that returns a Task
.
FileStream.ReadAsync()
returns a Task
, supports the asynchronous reading of data and it can be cancelled.
You can use it like this.
private async Task<string>ReadFileAsync(string filePath,CancellationToken token)
{
byte[] byteArray;
FileStream fileStream = null;
try
{
fileStream = File.Open(filePath, FileMode.Open);
byteArray = new byte[fileStream.Length];
await fileStream.ReadAsync(byteArray, 0, (int)fileStream.Length, token);
string text=Encoding.ASCII.GetString(byteArray);
return text;
}
finally
{
if (fileStream != null) fileStream.Dispose(); }
}
You can start the loading of data in the start button click handler.
private CancellationTokenSource cts;
private async void Start(object sender, RoutedEventArgs e)
{
List<string> texts = new List<string>();
string filename = @"c:\Temp\Io.txt";
cts = new CancellationTokenSource();
try
{
for (int i = 0; i < 100; i++)
{
string text = await ReadFileAsync(filename, cts.Token);
texts.Add(text);
}
}
catch (OperationCanceledException )
{
texts.Clear();
}
}
Use the cancel button click handler to cancel the file reads.The
CancellationTokenSource
is spent after cancellation and cannot be reused.
private void Cancel(object sender, RoutedEventArgs e)
{
if (cts != null) cts.Cancel();
}