Trouble understanding async and waiting

I am trying to understand async / await and Task in C #, but not impressive looking, despite watching videos on YouTube, reading documentation and following the plural course.

I was hoping that someone could help answer these somewhat abstract questions to help my brain.

1. Why do they say that async / await allows you to use the asynchonrous method when the async keyword does nothing on it and the await keyword adds a pause point? It does not add a suspension point, forcing the method to act synchronously, i.e. Complete the task marked by expectation before continuing.

2. Obviously, you should not use async void, except for event handlers, since you usually call the async method? It seems that to invoke an asynchronous method using the await keyword, the method / class that calls it itself should be marked as async. All the examples that I saw "initiated" the async void method with an event handler. How would you “avoid” this async / await package to run the method?

3.

public async Task SaveScreenshot(string filename, IWebDriver driver)
{
    var screenshot = driver.TakeScreenshot();
    await Task.Run(() =>
    {
        Thread.Sleep(2000);
        screenshot.SaveAsFile(filename, ScreenshotImageFormat.Bmp);
        Console.WriteLine("Screenshot saved");
    });
    Console.WriteLine("End of method");
}

1. . , Task.Run, Console.WriteLine("End of method"); . , , ? , 2, , " ". .

.

+7
3

, , .. , , , .

, , , "", "". await . "" " "; "" " ".

?

await.

"" async/await ?

. . ( ASP.NET MVC, Azure Functions/WebJobs, NUnit/xUnit/MSTest ..) , Task. ( WinForms, WPF, Xamarin Forms, ASP.NET WebForms ..) async void.

, . , , : , , , , .

, , . , async, /, async void. .

+8

:). , , - , "" .NET - , .

(1), async await , void Task/Task<T>. await .

, , . , . , WPF. , , , .

, async (, ), . ; Task Wait:

someAsyncMethod.Wait()

:

 var result = someAsyncMethod.Result;

, . , async - .

(3); ( await/async), .

+3

This is asynchronous because you do not need to wait for the method to return. In code, you can call the async method and save the task in a variable. Keep doing something else. Later, when the result of the method is required, you expect an answer (task).

// Synchronous method.
static void Main(string[] args)
{
    // Call async methods, but don't await them until needed.
    Task<string> task1 = DoAsync();
    Task<string> task2 = DoAsync();
    Task<string> task3 = DoAsync();

    // Do other stuff.

    // Now, it is time to await the async methods to finish.
    Task.WaitAll(task1, task2, task3);

    // Do something with the results.
    Console.WriteLine(task1.Result);
    Console.ReadKey();
}

private static async Task<string> DoAsync()
{
    Console.WriteLine("Started");
    await Task.Delay(3000);
    Console.WriteLine("Finished");

    return "Success";
}

// Output:
// Started
// Started
// Started
// Finished
// Finished
// Finished
// Success
+2
source

All Articles