Creating an Asynchronous File

How can I change this method to call it asynchronously?

private void Write(string fileName, data) { File.WriteAllText(fileName, data); } 
+6
source share
2 answers

Take a look at FileStream.WriteAsync (note that you should use the correct overload, which takes a bool indicating whether it should start async:)

 public async Task WriteAsync(string data) { var buffer = Encoding.ASCII.GetBytes(data); using (var fs = new FileStream(@"File", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, buffer.Length, true)) { await fs.WriteAsync(buffer, 0, buffer.Length); } } 

Edit

If you want to use string data and avoid conversion to byte[] , you can use the more abstract and less detailed StreamWriter.WriteAsync overload, which takes a string:

 public async Task WriteAsync(string data) { using (var sw = new StreamWriter(@"FileLocation")) { await sw.WriteAsync(data); } } 
+10
source

You can call the method inside Task as follows:

 Task.Factory.StartNew(() => File.WriteAllText("test.txt","text")); 

There are many ways to run a task, and this is just one of them, you read here .

+2
source

Source: https://habr.com/ru/post/974408/


All Articles