Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is safe to not await inside a using block?

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);
    }
}
like image 731
Bart Calixto Avatar asked Apr 21 '16 00:04

Bart Calixto


People also ask

Can await be used in a block?

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.

Where can async/await be used?

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?

What is the difference between await and lock in JavaScript?

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.

What are the problems with await in ASP NET?

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).


1 Answers

No, it is not safe, if you don't await then file will be disposed before the copy operation completes.

like image 88
Scott Chamberlain Avatar answered Oct 12 '22 10:10

Scott Chamberlain