当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: