In this section, we will learn how to perform I/O operations on a file asynchronously. This can be helpful in scenarios when the data that we are writing to the file is large.
The following code implementation shows how to write data to a file asynchronously. Please note that we must use the FileStream object to execute file I/O operations asynchronously:
public async Task CreateFile()
{
string path =@"C:UCN Code BaseProgramming-in-C-Exam-70-483-MCSD- GuideBook70483SamplesChapter 20New.txt";
using (FileStream stream = new FileStream(path,FileMode.Create,
FileAccess.Write, FileShare.None, 4096, true))
{
byte[] data = new byte[100000];
new Random().NextBytes(data);
await stream.WriteAsync(data, 0, data.Length);
}
}
In the preceding code implementation, we are creating a new file in a given directory location. The calling function does not require a value to be returned, so we have just set the return type as Task. To create the file and write data to it, we have used a FileStream object. For a detailed analysis of the properties passed in the constructor of the class, please refer to the following link: https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.7.2.
After creating the object, we are generating a random sequence of bytes and are then writing it asynchronously to the FileStream object.
For a code implementation related to calling web requests asynchronously, we can refer to the implementation in the previous example where we created an object called HttpClient and made a call asynchronously.
In the next section, we will learn how to execute multiple I/O operations asynchronously and in a parallel manner.
This is quite useful in scenarios where the application must wait for the completion of different functions that are executing in parallel.