In this code, is it safe to not await the CopyToAsync
or the stream could be disposed before the actual copy is done?
public Task SaveAsync(Stream source, string filepath)
{
using (var file = File.OpenWrite(filepath))
{
return source.CopyToAsync(file);
}
}
An await expression cannot occur in the body of a synchronous function, in a query expression, in the block of a lock statement, or in an unsafe context. Since the introduction of C# 5, async/await is used pretty much everywhere.
An await expression cannot occur in the body of a synchronous function, in a query expression, in the block of a lock statement, or in an unsafe context. Since the introduction of C# 5, async / await is used pretty much everywhere. And why not?
The lock keyword can only be used to synchronize synchronous code. From MSDN: An await expression cannot occur in the body of a synchronous function, in a query expression, in the block of a lock statement, or in an unsafe context. Since the introduction of C# 5, async / await is used pretty much everywhere.
There are (at least) four efficiency problems introduced as soon as you use await with Task.Run in ASP.NET: Extra (unnecessary) thread switching to the Task.Run thread pool thread. Similarly, when that thread finishes the request, it has to enter the request context (which is not an actual thread switch but does have overhead).
No, it is not safe, if you don't await then file
will be disposed before the copy operation completes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With