Asynchronous File Access - C# - Microsoft Learn
Asynchronous File Access - C# - Microsoft Learn
Article • 02/13/2023
You can use the async feature to access files. By using the async feature, you can call into
asynchronous methods without using callbacks or splitting your code across multiple methods or
lambda expressions. To make synchronous code asynchronous, you just call an asynchronous method
instead of a synchronous method and add a few keywords to the code.
You might consider the following reasons for adding asynchrony to file access calls:
" Asynchrony makes UI applications more responsive because the UI thread that launches the
operation can perform other work. If the UI thread must execute code that takes a long time (for
example, more than 50 milliseconds), the UI may freeze until the I/O is complete and the UI
thread can again process keyboard and mouse input and other events.
" Asynchrony improves the scalability of ASP.NET and other server-based applications by reducing
the need for threads. If the application uses a dedicated thread per response and a thousand
requests are being handled simultaneously, a thousand threads are needed. Asynchronous
operations often don't need to use a thread during the wait. They use the existing I/O completion
thread briefly at the end.
" The latency of a file access operation might be very low under current conditions, but the latency
may greatly increase in the future. For example, a file may be moved to a server that's across the
world.
" The added overhead of using the Async feature is small.
" Asynchronous tasks can easily be run in parallel.
You can't use this option with StreamReader and StreamWriter if you open them directly by specifying
a file path. However, you can use this option if you provide them a Stream that the FileStream class
opened. Asynchronous calls are faster in UI apps even if a thread pool thread is blocked, because the
UI thread isn't blocked during the wait.
Write text
The following examples write 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.
The async modifier is in the definition of methods that use the await statement.
Simple example
C#
The first statement returns a task and causes file processing to start. The second statement with the
await causes the method to immediately exit and return a different task. When the file processing
later completes, execution returns to the statement that follows the await.
Read text
The following examples read text from a file.
Simple example
C#
Console.WriteLine(text);
}
C#
return sb.ToString();
}
Simple example
C#
writeTaskList.Add(File.WriteAllTextAsync(filePath, text));
}
await Task.WhenAll(writeTaskList);
}
The example closes all FileStream instances in a finally block after the tasks are complete. If each
FileStream was instead created in a using statement, the FileStream might be disposed of before
Any performance boost is almost entirely from the parallel processing and not the asynchronous
processing. The advantages of asynchrony are that it doesn't tie up multiple threads, and that it
doesn't tie up the user interface thread.
C#
try
{
string folder = Directory.CreateDirectory("tempfolder").Name;
IList<Task> writeTaskList = new List<Task>();
var sourceStream =
new FileStream(
filePath,
FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true);
writeTaskList.Add(writeTask);
}
await Task.WhenAll(writeTaskList);
}
finally
{
foreach (FileStream sourceStream in sourceStreams)
{
sourceStream.Close();
}
}
}
When using the WriteAsync and ReadAsync methods, you can specify a CancellationToken, which you
can use to cancel the operation mid-stream. For more information, see Cancellation in managed
threads.
See also
Asynchronous programming with async and await (C#)
Async return types (C#)
6 Collaborate with us on
GitHub .NET feedback
.NET is an open source project. Select a link to
The source for this content can be
provide feedback:
found on GitHub, where you can
also create and review issues and
Open a documentation issue
pull requests. For more
information, see our contributor
Provide product feedback
guide.