Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lambda expression instead of asynchronous version of Write method

So I've been doing module about asynchronous programming in C# on EDX. The task was to make the method WriteText asynchronous.

I changed the definition of method to private async, and then I had this prompt about using await keyword in the method to make it asynchronous.

I did this way:

using (FileStream sourceStream = new FileStream(filePath,
            FileMode.Append, FileAccess.Write, FileShare.None,
            bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        };

However, I also did this way using lambda expression and there was no prompt anymore.

 Task task1 = Task.Run(() =>
        {
            using (FileStream sourceStream = new FileStream(filePath,
                   FileMode.Append, FileAccess.Write, FileShare.None,
                   bufferSize: 4096))
            {
                sourceStream.Write(encodedText, 0, encodedText.Length);
            };
        });
        await task1;

I know the first way is proper, but my question is, if the second way is also good? Does it make the method asynchronous? I believe your answer will help me to clarify the concept of asynchronous programming.


1 Answers

No, the second way is often called "fake async", it is much much preferred to do the first way.

If a caller wants to run your function on a background thread, let them call your function inside a Task.Run don't wrap up the Task.Run for them.

like image 163
Scott Chamberlain Avatar answered Apr 23 '26 18:04

Scott Chamberlain