SomeUser SomeUser - 2 months ago 12
C# Question

Why should I prefer using API async fucntions over wrapping synchronous ones with Task.Run?

I know there is a difference between this code:

var streamWriter = new StreamWriter("something.txt");
streamWriter.WriteAsync("text");


and this:

var streamWriter = new StreamWriter("something.txt");
Task.Run(()=> streamWriter.Write("text"));


the first one makes much more sense.

and in different scenario when I am awaiting a result, this code:

var streamReader = new StreamReader("something.txt")
char[] chars = new char[10];

Task<int> task = streamReader.ReadAsync(chars, 0, chars.Length);
//Do something...

int num = await task;
//Do something with num...


makes much more sense than this:

var streamReader = new StreamReader("something.txt")
char[] chars = new char[10];

Task<int> task = Task.Run(()=>streamReader.Read(chars, 0, chars.Length));
//Do something...

int num = await task;
//Do something with num...


I guess the use of the built in async API is better not only in clarity and it actually manages the
ThreadPool
threads better and in more efficient way than having a
ThreadPool
thread waiting for no reason.

Is it right?

Answer

A synchronous call wrapped in a Task.Run will block a thread pool thread for the duration of that operation. A truly asynchronous implementation will not.

With streams in particular, whether the operation is "truly asynchronous" can be a bit tricky to determine. For example, network streams are always truly asynchronous, memory streams are never truly asynchronous, and file streams are only truly asynchronous if you pass a special flag to their constructor.

Comments