-2

I was looking at some of the example code on Microsoft Playwright and in the example code, there is this bit

public static async Task Main()
{
    using var playwright = await Playwright.CreateAsync();
    await using var browser = await playwright.Chromium.LaunchAsync();
    var page = await browser.NewPageAsync();
    await page.GotoAsync("https://playwright.dev/dotnet");
    await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });
}

What does the first await in line 4 do? I've tried searching for it but I can't find any documentation on it.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • The `await using` syntax means the disposal uses `DisposeAsync` instead of `Dispose`. – Matthew Nov 18 '21 at 12:39
  • Does this answer your question? [C# 8 understanding await using syntax](https://stackoverflow.com/questions/58791938/c-sharp-8-understanding-await-using-syntax) – Andrew McClement Nov 18 '21 at 12:43
  • There's not really an await on the left side of the assignment. You could split this up into two lines for clarity `var browser = await playwright.Chromium.LaunchAsync();` and then `await using browser;` – DavidG Nov 18 '21 at 12:44
  • Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content ([under the CC BY-SA 4.0 license](https://stackoverflow.com/help/licensing)). By SE policy, any vandalism will be reverted. – Luca Kiebel Feb 17 '22 at 13:24

2 Answers2

1

If you are talking about:

await using var browser = await playwright.Chromium.LaunchAsync();

line, then this is not just an assignment but two features added in C# 8 combined - asynchronous disposable:

Starting with C# 8.0, the language supports asynchronous disposable types that implement the System.IAsyncDisposable interface. You use the await using statement to work with an asynchronously disposable object.

and using declarations:

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

From the docs:

You use the await using statement to work with an asynchronously disposable object, that is, an object of a type that implements an IAsyncDisposable interface. For more information, see the Using async disposable section of the Implement a DisposeAsync method article.

IAsyncDisposable is used for releasing unmanaged resources in asynchronous manner.

Maroun
  • 94,125
  • 30
  • 188
  • 241