You have the following code. (Line numbers are included for reference only).
You need to complete the WriteTextAsync method. The solution must ensure that the code is not blocked while
the file is being written.
Which code should you insert at line 12?
A.
Option A
B.
Option B
C.
Option C
D.
Option D
Explanation:
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
The following example has the statement await sourceStream.WriteAsync(encodedText, 0,
encodedText.Length);, which is a contraction of the following two statements:
Task theTask = sourceStream.WriteAsync(encodedText, 0, encodedText.Length);await theTask;
Example: The following example writes text to a file. At each await statement, the method immediately exits.
When the file I/O is complete, the method resumes at the statement that follows the await statement. Note that
the async modifier is in the definition of methods that use the await statement.
public async void ProcessWrite()
{
string filePath = @”temp2.txt”;
string text = “Hello World\\r\\n”;
await WriteTextAsync(filePath, text);
}
private async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
Using Async for File Access (C# and Visual Basic)
https://msdn.microsoft.com/en-us/library/jj155757.aspx
Its a dumb (yet correct) answer. this structure:
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
completely nullifies any asynchronous processing…