* Fix issues.

**This commit should be reviewed carefully**

There are three issues open on this article. Fix two of them first:

Fixes #26446: Clarify where to find the HttClient class.
Fixes ##27720: Add call to `ToArray` to force eager evaluation of a LINQ query. Explain why this was added.

The other issue may require a new article to limit the number of concurrent tasks.

* Move async article

Move the scenarios overview to the new section.

* Fix issues before moving file

**This commit should be reviewed**

There are six issues open on this file.  Fix the following:

Fixes #20680 Clarify that starting a task and immediately awaying doesn't result in any faster results.
Fixes #33641: Explain why the finished task must also be awaited.

* Move existing async overview article.

Move this article under the new async section.

* move async task model

* Move async return types article.

move samples

* Fix open issues on this page.

**This commit should be reviewed**

This page has one open issue.

Fixes #32782:  Add a clarification to the example code to note that the while loop will complete.

* move article on processing multiple tasks as they finish

* Move async file access article and sample.

* Fix open issues on this article

**This commit should be reviewed**

The only open issue is #27061

Update the sample, and add text to explain the update.

* Move cancellation articles

Move the tutorials on cancelling a running task.

* Fix open issues on tutorial

**This commit should be reviewed**

There's only one open issue on this tutorial:

* Move async streams tutorial

* fix warnings

restore and move images

These images were under the old C# folder. They are only used in the VB docs, so restore them here.

* update breadcrumb, redirections and metadata.

** This commit should be reviewed**

* Apply suggestions from code review

Co-authored-by: David Pine <david.pine@microsoft.com>

* Respond to feedback. Remove specific .NET 6.0 comments.

---------

Co-authored-by: David Pine <david.pine@microsoft.com>
This commit is contained in:
Bill Wagner 2023-02-13 11:07:07 -05:00 коммит произвёл GitHub
Родитель 77499a74e2
Коммит 53bc3afbcc
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
84 изменённых файлов: 213 добавлений и 158 удалений

Просмотреть файл

@ -56,6 +56,10 @@
"source_path_from_root": "/redirections/proposals/csharp-10.0/generic-attributes.md",
"redirect_url": "/dotnet/csharp/language-reference/proposals/csharp-11.0/generic-attributes"
},
{
"source_path_from_root": "/docs/csharp/async.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/basic-types.md",
"redirect_url": "/dotnet/csharp/fundamentals/types"
@ -1224,35 +1228,63 @@
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/asynchronous-programming-with-async-and-await.md",
"redirect_url": "/dotnet/csharp/async/"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/cancel-remaining-async-tasks-after-one-is-complete.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model#BKMK_WhatHappensUnderstandinganAsyncMethod"
"redirect_url": "/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model#BKMK_WhatHappensUnderstandinganAsyncMethod"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/fine-tuning-your-async-application.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/handling-reentrancy-in-async-apps.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md",
"redirect_url": "/dotnet/csharp/programming-guide/concepts/async"
"redirect_url": "/dotnet/csharp/asynchronous-programming"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/async-return-types.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/async-return-types"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/cancel-async-tasks-after-a-period-of-time"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/index.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/async-scenarios"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/task-asynchronous-programming-model.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/using-async-for-file-access.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/using-async-for-file-access"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/cancel-an-async-task-or-a-list-of-tasks"
},
{
"source_path_from_root": "/docs/csharp/programming-guide/concepts/attributes/attributeusage.md",
@ -2780,6 +2812,10 @@
"source_path_from_root": "/docs/csharp/tutorials/exploration/top-level-statements.md",
"redirect_url": "/dotnet/csharp/whats-new/tutorials/top-level-statements"
},
{
"source_path_from_root": "/docs/csharp/tutorials/generate-consume-asynchronous-stream.md",
"redirect_url": "/dotnet/csharp/asynchronous-programming/generate-consume-asynchronous-stream"
},
{
"source_path_from_root": "/docs/csharp/tutorials/index.md",
"redirect_url": "/dotnet/csharp/fundamentals/tutorials/how-to-display-command-line-arguments"

Просмотреть файл

@ -221,7 +221,7 @@ pull_request:
- path: "(?i).*docs\/csharp\/programming-guide\/concepts\/expression-trees.*"
run:
- labels-add: ["dotnet-csharp/prod", "csharp-advanced-concepts/tech"]
- path: "(?i).*docs\/csharp\/programming-guide\/concepts\/async.*"
- path: "(?i).*docs\/csharp\/asynchronous-programming\/.*"
run:
- labels-add: ["dotnet-csharp/prod", "csharp-async/tech"]
- path: "(?i).*docs\/csharp\/programming-guide\/concepts\/linq.*"

Просмотреть файл

@ -501,6 +501,8 @@
"docs/csharp/how-to/**/**.md": "csharp-fundamentals",
"docs/csharp/linq/**/**.md": "csharp-linq",
"docs/csharp/fundamentals/**/**.md": "csharp-fundamentals",
"docs/csharp/asynchronous-programming/**/**.md": "csharp-async",
"docs/csharp/advanced-topics/**/**.md": "csharp-advanced-concepts",
"docs/csharp/language-reference/unsafe-code.md": "csharp-advanced-concepts",
"docs/csharp/programming-guide/indexers/**/**.md": "csharp-fundamentals",
"docs/csharp/programming-guide/generics/**/**.md": "csharp-fundamentals",
@ -514,7 +516,6 @@
"docs/csharp/programming-guide/concepts/covariance-contravariance/**/**.md": "csharp-advanced-concepts",
"docs/csharp/programming-guide/concepts/serialization/**/**.md": "csharp-fundamentals",
"docs/csharp/programming-guide/concepts/expression-trees/**/**.md": "csharp-advanced-concepts",
"docs/csharp/programming-guide/concepts/async/**/**.md": "csharp-async",
"docs/csharp/programming-guide/concepts/linq/**/**.md": "csharp-linq",
"docs/csharp/programming-guide/concepts/attributes/**/**.md": "csharp-fundamentals",
"docs/csharp/programming-guide/xmldoc/**/**.md": "csharp-fundamentals",

Просмотреть файл

@ -283,6 +283,9 @@ items:
- name: Tutorials
tocHref: /dotnet/csharp/whats-new/tutorials/
topicHref: /dotnet/csharp/whats-new/tutorials/records
- name: Asynchronous programming
tocHref: /dotnet/csharp/asynchronous-programming
topicHref: /dotnet/csharp/asynchronous-programming/index
- name: Tutorials
tocHref: /dotnet/csharp/tutorials/
topicHref: /dotnet/csharp/tutorials/index
@ -324,9 +327,6 @@ items:
tocHref: /dotnet/csharp/programming-guide/concepts/
topicHref: /dotnet/csharp/programming-guide/concepts/index
items:
- name: Asynchronous programming
tocHref: /dotnet/csharp/programming-guide/concepts/async/
topicHref: /dotnet/csharp/programming-guide/concepts/async/index
- name: Attributes
tocHref: /dotnet/csharp/programming-guide/concepts/attributes/
topicHref: /dotnet/csharp/programming-guide/concepts/attributes/index

Просмотреть файл

@ -189,7 +189,7 @@ In the preceding code, the `implementationFactory` is given a lambda expression
:::code language="csharp" source="snippets/configuration/di-anti-patterns/Program.cs" id="AsyncDeadlockTwo":::
For more information on asynchronous guidance, see [Asynchronous programming: Important info and advice](../../csharp/async.md#important-info-and-advice). For more information debugging deadlocks, see [Debug a deadlock in .NET](../diagnostics/debug-deadlock.md).
For more information on asynchronous guidance, see [Asynchronous programming: Important info and advice](../../csharp/asynchronous-programming/async-scenarios.md#important-info-and-advice). For more information debugging deadlocks, see [Debug a deadlock in .NET](../diagnostics/debug-deadlock.md).
When you're running this anti-pattern and the deadlock occurs, you can view the two threads waiting from Visual Studio's Parallel Stacks window. For more information, see [View threads and tasks in the Parallel Stacks window](/visualstudio/debugger/using-the-parallel-stacks-window).

Просмотреть файл

@ -39,7 +39,7 @@ recommendations: false
.NET features allow developers to productively write reliable and performant code.
* [Asynchronous code](../csharp/programming-guide/concepts/async/index.md)
* [Asynchronous code](../csharp/asynchronous-programming/index.md)
* [Attributes](../standard/attributes/index.md)
* [Reflection](../csharp/programming-guide/concepts/reflection.md)
* [Code analyzers](../fundamentals/code-analysis/overview.md)

Просмотреть файл

@ -27,7 +27,7 @@ C# 8.0 is also part of this release, which includes the [nullable reference type
Tutorials related to C# 8.0 language features:
- [Tutorial: Express your design intent more clearly with nullable and non-nullable reference types](../../csharp/tutorials/nullable-reference-types.md)
- [Tutorial: Generate and consume async streams using C# 8.0 and .NET Core 3.0](../../csharp/tutorials/generate-consume-asynchronous-stream.md)
- [Tutorial: Generate and consume async streams using C# 8.0 and .NET Core 3.0](../../csharp/asynchronous-programming/generate-consume-asynchronous-stream.md)
- [Tutorial: Use pattern matching to build type-driven and data-driven algorithms](../../csharp/fundamentals/tutorials/pattern-matching.md)
Language enhancements were added to support the following API features detailed below:
@ -463,7 +463,7 @@ async IAsyncEnumerable<int> GetBigResultsAsync()
In addition to being able to `await foreach`, you can also create async iterators, for example, an iterator that returns an `IAsyncEnumerable/IAsyncEnumerator` that you can both `await` and `yield` in. For objects that need to be disposed, you can use `IAsyncDisposable`, which various BCL types implement, such as `Stream` and `Timer`.
For more information, see the [async streams tutorial](../../csharp/tutorials/generate-consume-asynchronous-stream.md).
For more information, see the [async streams tutorial](../../csharp/asynchronous-programming/generate-consume-asynchronous-stream.md).
### IEEE Floating-point

Просмотреть файл

@ -1,8 +1,7 @@
---
title: Async return types (C#)
title: Async return types
description: Learn about the return types that async methods can have in C# with code examples for each type.
ms.date: 07/02/2021
ms.assetid: ddb2539c-c898-48c1-ad92-245e4a996df8
ms.date: 02/08/2023
---
# Async return types (C#)
@ -43,13 +42,13 @@ The following code separates calling the `WaitAndApologizeAsync` method from awa
## Task\<TResult\> return type
The <xref:System.Threading.Tasks.Task%601> return type is used for an async method that contains a [return](../../../language-reference/statements/jump-statements.md#the-return-statement) statement in which the operand is `TResult`.
The <xref:System.Threading.Tasks.Task%601> return type is used for an async method that contains a [return](../language-reference/statements/jump-statements.md#the-return-statement) statement in which the operand is `TResult`.
In the following example, the `GetLeisureHoursAsync` method contains a `return` statement that returns an integer. The method declaration must specify a return type of `Task<int>`. The <xref:System.Threading.Tasks.Task.FromResult%2A> async method is a placeholder for an operation that returns a <xref:System.DateTime.DayOfWeek>.
:::code language="csharp" source="snippets/async-return-types/async-returns1.cs" ID="LeisureHours":::
When `GetLeisureHoursAsync` is called from within an await expression in the `ShowTodaysInfo` method, the await expression retrieves the integer value (the value of `leisureHours`) that's stored in the task returned by the `GetLeisureHours` method. For more information about await expressions, see [await](../../../language-reference/operators/await.md).
When `GetLeisureHoursAsync` is called from within an await expression in the `ShowTodaysInfo` method, the await expression retrieves the integer value (the value of `leisureHours`) that's stored in the task returned by the `GetLeisureHours` method. For more information about await expressions, see [await](../language-reference/operators/await.md).
You can better understand how `await` retrieves the result from a `Task<T>` by separating the call to `GetLeisureHoursAsync` from the application of `await`, as the following code shows. A call to method `GetLeisureHoursAsync` that isn't immediately awaited returns a `Task<int>`, as you would expect from the declaration of the method. The task is assigned to the `getLeisureHoursTask` variable in the example. Because `getLeisureHoursTask` is a <xref:System.Threading.Tasks.Task%601>, it contains a <xref:System.Threading.Tasks.Task%601.Result> property of type `TResult`. In this case, `TResult` represents an integer type. When `await` is applied to `getLeisureHoursTask`, the await expression evaluates to the contents of the <xref:System.Threading.Tasks.Task%601.Result%2A> property of `getLeisureHoursTask`. The value is assigned to the `ret` variable.
@ -66,7 +65,7 @@ You use the `void` return type in asynchronous event handlers, which require a `
The caller of a void-returning async method can't catch exceptions thrown from the method. Such unhandled exceptions are likely to cause your application to fail. If a method that returns a <xref:System.Threading.Tasks.Task> or <xref:System.Threading.Tasks.Task%601> throws an exception, the exception is stored in the returned task. The exception is rethrown when the task is awaited. Make sure that any async method that can produce an exception has a return type of <xref:System.Threading.Tasks.Task> or <xref:System.Threading.Tasks.Task%601> and that calls to the method are awaited.
For more information about how to catch exceptions in async methods, see the [Exceptions in async methods](../../../language-reference/keywords/try-catch.md#exceptions-in-async-methods) section of the [try-catch](../../../language-reference/keywords/try-catch.md) article.
For more information about how to catch exceptions in async methods, see the [Exceptions in async methods](../language-reference/keywords/try-catch.md#exceptions-in-async-methods) section of the [try-catch](../language-reference/keywords/try-catch.md) article.
The following example shows the behavior of an async event handler. In the example code, an async event handler must let the main thread know when it finishes. Then the main thread can wait for an async event handler to complete before exiting the program.
@ -74,7 +73,7 @@ The following example shows the behavior of an async event handler. In the examp
## Generalized async return types and ValueTask\<TResult\>
An async method can return any type that has an accessible `GetAwaiter` method that returns an instance of an *awaiter type*. In addition, the type returned from the `GetAwaiter` method must have the <xref:System.Runtime.CompilerServices.AsyncMethodBuilderAttribute?displayProperty=nameWithType> attribute. You can learn more in the article on [Attributes read by the compiler](../../../language-reference/attributes/general.md#asyncmethodbuilder-attribute) or the feature spec for [Task like return types](~/_csharplang/proposals/csharp-7.0/task-types.md).
An async method can return any type that has an accessible `GetAwaiter` method that returns an instance of an *awaiter type*. In addition, the type returned from the `GetAwaiter` method must have the <xref:System.Runtime.CompilerServices.AsyncMethodBuilderAttribute?displayProperty=nameWithType> attribute. You can learn more in the article on [Attributes read by the compiler](../language-reference/attributes/general.md#asyncmethodbuilder-attribute) or the feature spec for [Task like return types](~/_csharplang/proposals/csharp-7.0/task-types.md).
This feature is the complement to [awaitable expressions](~/_csharpstandard/standard/expressions.md#11882-awaitable-expressions), which describes the requirements for the operand of `await`. Generalized async return types enable the compiler to generate `async` methods that return different types. Generalized async return types enabled performance improvements in the .NET libraries. Because <xref:System.Threading.Tasks.Task> and <xref:System.Threading.Tasks.Task%601> are reference types, memory allocation in performance-critical paths, particularly when allocations occur in tight loops, can adversely affect performance. Support for generalized return types means that you can return a lightweight value type instead of a reference type to avoid additional memory allocations.
@ -99,5 +98,5 @@ The preceding example reads lines from a string asynchronously. Once each line i
- <xref:System.Threading.Tasks.Task.FromResult%2A>
- [Process asynchronous tasks as they complete](start-multiple-async-tasks-and-process-them-as-they-complete.md)
- [Asynchronous programming with async and await (C#)](index.md)
- [async](../../../language-reference/keywords/async.md)
- [await](../../../language-reference/operators/await.md)
- [async](../language-reference/keywords/async.md)
- [await](../language-reference/operators/await.md)

Просмотреть файл

@ -2,15 +2,14 @@
title: Asynchronous programming - C#
description: Learn about the C# language-level asynchronous programming model provided by .NET Core.
author: BillWagner
ms.date: 05/20/2020
ms.date: 02/08/2023
ms.technology: csharp-async
ms.assetid: b878c34c-a78f-419e-a594-a2b44fa521a4
---
# Asynchronous programming
If you have any I/O-bound needs (such as requesting data from a network, accessing a database, or reading and writing to a file system), you'll want to utilize asynchronous programming. You could also have CPU-bound code, such as performing an expensive calculation, which is also a good scenario for writing async code.
C# has a language-level asynchronous programming model, which allows for easily writing asynchronous code without having to juggle callbacks or conform to a library that supports asynchrony. It follows what is known as the [Task-based Asynchronous Pattern (TAP)](../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md).
C# has a language-level asynchronous programming model, which allows for easily writing asynchronous code without having to juggle callbacks or conform to a library that supports asynchrony. It follows what is known as the [Task-based Asynchronous Pattern (TAP)](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md).
## Overview of the asynchronous model
@ -19,11 +18,11 @@ The core of async programming is the `Task` and `Task<T>` objects, which model a
- For I/O-bound code, you await an operation that returns a `Task` or `Task<T>` inside of an `async` method.
- For CPU-bound code, you await an operation that is started on a background thread with the <xref:System.Threading.Tasks.Task.Run%2A?displayProperty=nameWithType> method.
The `await` keyword is where the magic happens. It yields control to the caller of the method that performed `await`, and it ultimately allows a UI to be responsive or a service to be elastic. While [there are ways](../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) to approach async code other than `async` and `await`, this article focuses on the language-level constructs.
The `await` keyword is where the magic happens. It yields control to the caller of the method that performed `await`, and it ultimately allows a UI to be responsive or a service to be elastic. While [there are ways](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) to approach async code other than `async` and `await`, this article focuses on the language-level constructs.
### I/O-bound example: Download data from a web service
You may need to download some data from a web service when a button is pressed but don't want to block the UI thread. It can be accomplished like this:
You may need to download some data from a web service when a button is pressed but don't want to block the UI thread. It can be accomplished like this, using the <xref:System.Net.Http.HttpClient?displayProperty=fullName> class:
```csharp
private readonly HttpClient _httpClient = new HttpClient();
@ -97,7 +96,7 @@ Here are two questions you should ask before you write any code:
If the work you have is **I/O-bound**, use `async` and `await` *without* `Task.Run`. You *should not* use the Task Parallel Library.
If the work you have is **CPU-bound** and you care about responsiveness, use `async` and `await`, but spawn off the work on another thread *with* `Task.Run`. If the work is appropriate for concurrency and parallelism, also consider using the [Task Parallel Library](../standard/parallel-programming/task-parallel-library-tpl.md).
If the work you have is **CPU-bound** and you care about responsiveness, use `async` and `await`, but spawn off the work on another thread *with* `Task.Run`. If the work is appropriate for concurrency and parallelism, also consider using the [Task Parallel Library](../../standard/parallel-programming/task-parallel-library-tpl.md).
Additionally, you should always measure the execution of your code. For example, you may find yourself in a situation where your CPU-bound work is not costly enough compared with the overhead of context switches when multithreading. Every choice has its tradeoff, and you should pick the correct tradeoff for your situation.
@ -194,12 +193,12 @@ public async Task<User> GetUserAsync(int userId)
public static async Task<User[]> GetUsersAsync(IEnumerable<int> userIds)
{
var getUserTasks = userIds.Select(id => GetUserAsync(id));
var getUserTasks = userIds.Select(id => GetUserAsync(id)).ToArray();
return await Task.WhenAll(getUserTasks);
}
```
Although it's less code, use caution when mixing LINQ with asynchronous code. Because LINQ uses deferred (lazy) execution, async calls won't happen immediately as they do in a `foreach` loop unless you force the generated sequence to iterate with a call to `.ToList()` or `.ToArray()`.
Although it's less code, use caution when mixing LINQ with asynchronous code. Because LINQ uses deferred (lazy) execution, async calls won't happen immediately as they do in a `foreach` loop unless you force the generated sequence to iterate with a call to `.ToList()` or `.ToArray()`. The above example uses <xref:System.Linq.Enumerable.ToArray%2A?displayProperty=nameWithType> to perform the query eagerly and store the results in an array. That forces the code `id => GetUserAsync(id)` to run and start the task.
## Important info and advice
@ -238,7 +237,7 @@ With async programming, there are some details to keep in mind that can prevent
* **Consider using** `ValueTask` **where possible**
Returning a `Task` object from async methods can introduce performance bottlenecks in certain paths. `Task` is a reference type, so using it means allocating an object. In cases where a method declared with the `async` modifier returns a cached result or completes synchronously, the extra allocations can become a significant time cost in performance critical sections of code. It can become costly if those allocations occur in tight loops. For more information, see [generalized async return types](language-reference/keywords/async.md#return-types).
Returning a `Task` object from async methods can introduce performance bottlenecks in certain paths. `Task` is a reference type, so using it means allocating an object. In cases where a method declared with the `async` modifier returns a cached result or completes synchronously, the extra allocations can become a significant time cost in performance critical sections of code. It can become costly if those allocations occur in tight loops. For more information, see [generalized async return types](../language-reference/keywords/async.md#return-types).
* **Consider using** `ConfigureAwait(false)`
@ -259,4 +258,4 @@ A recommended goal is to achieve complete or near-complete [Referential Transpar
## Other resources
* [The Task asynchronous programming model (C#)](./programming-guide/concepts/async/task-asynchronous-programming-model.md).
* [The Task asynchronous programming model (C#)](task-asynchronous-programming-model.md).

Просмотреть файл

@ -1,13 +1,11 @@
---
title: Cancel a list of tasks (C#)
title: Cancel a list of tasks
description: Learn how to use cancellation tokens to signal a cancellation request to a list of tasks.
ms.date: 02/03/2021
ms.date: 02/09/2023
ms.topic: tutorial
ms.assetid: eec32dbb-70ea-4c88-bd27-fa2e34546914
recommendations: false
---
# Cancel a list of tasks (C#)
# Cancel a list of tasks
You can cancel an async console application if you don't want to wait for it to finish. By following the example in this topic, you can add a cancellation to an application that downloads the contents of a list of websites. You can cancel many tasks by associating the <xref:System.Threading.CancellationTokenSource> instance with each task. If you select the <kbd>Enter</kbd> key, you cancel all tasks that aren't yet complete.
@ -29,7 +27,7 @@ This tutorial requires the following:
### Create example application
Create a new .NET Core console application. You can create one by using the [`dotnet new console`](../../../../core/tools/dotnet-new-sdk-templates.md#console) command or from [Visual Studio](/visualstudio/install/install-visual-studio). Open the *Program.cs* file in your favorite code editor.
Create a new .NET Core console application. You can create one by using the [`dotnet new console`](../../core/tools/dotnet-new-sdk-templates.md#console) command or from [Visual Studio](/visualstudio/install/install-visual-studio). Open the *Program.cs* file in your favorite code editor.
### Replace using statements
@ -103,15 +101,27 @@ static async Task Main()
s_cts.Cancel();
});
Task sumPageSizesTask = SumPageSizesAsync();
await Task.WhenAny(new[] { cancelTask, sumPageSizesTask });
Task finishedTask = await Task.WhenAny(new[] { cancelTask, sumPageSizesTask });
if (finishedTask == cancelTask)
{
// wait for the cancellation to take place:
try
{
await sumPageSizesTask;
Console.WriteLine("Download task completed before cancel request was processed.");
}
catch (TaskCanceledException)
{
Console.WriteLine("Download task has been cancelled.");
}
}
Console.WriteLine("Application ending.");
}
```
The updated `Main` method is now considered an [Async main](../../../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It writes a few instructional messages to the console, then declares a <xref:System.Threading.Tasks.Task> instance named `cancelTask`, which will read console key strokes. If the <kbd>Enter</kbd> key is pressed, a call to <xref:System.Threading.CancellationTokenSource.Cancel?displayProperty=nameWithType> is made. This will signal cancellation. Next, the `sumPageSizesTask` variable is assigned from the `SumPageSizesAsync` method. Both tasks are then passed to <xref:System.Threading.Tasks.Task.WhenAny(System.Threading.Tasks.Task[])?displayProperty=nameWithType>, which will continue when any of the two tasks have completed.
The updated `Main` method is now considered an [Async main](../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It writes a few instructional messages to the console, then declares a <xref:System.Threading.Tasks.Task> instance named `cancelTask`, which will read console key strokes. If the <kbd>Enter</kbd> key is pressed, a call to <xref:System.Threading.CancellationTokenSource.Cancel?displayProperty=nameWithType> is made. This will signal cancellation. Next, the `sumPageSizesTask` variable is assigned from the `SumPageSizesAsync` method. Both tasks are then passed to <xref:System.Threading.Tasks.Task.WhenAny(System.Threading.Tasks.Task[])?displayProperty=nameWithType>, which will continue when any of the two tasks have completed.
The next block of code ensures that the application doesn't exit until the cancellation has been processed. If the first task to complete is the `cancelTask`, the `sumPageSizeTask` is awaited. If it was cancelled, when awaited it throws a <xref:System.Threading.Tasks.TaskCanceledException?displayProperty=nameWithType>. The block catches that exception, and prints a message.
## Create the asynchronous sum page sizes method
@ -187,7 +197,7 @@ Application ending.
The following code is the complete text of the *Program.cs* file for the example.
:::code language="csharp" source="snippets/cancel-tasks/cancel-tasks/Program.cs":::
:::code language="csharp" source="snippets/cancel-tasks/Program.cs":::
## See also

Просмотреть файл

@ -1,12 +1,11 @@
---
title: Cancel async tasks after a period of time (C#)"
title: Cancel async tasks after a period of time"
description: Learn how to schedule cancellation of any associated tasks that are not completed within a period of time.
ms.date: 02/03/2021
ms.date: 02/09/2023
ms.topic: tutorial
ms.assetid: 194282c2-399f-46da-a7a6-96674e00b0b3
---
# Cancel async tasks after a period of time (C#)
# Cancel async tasks after a period of time
You can cancel an asynchronous operation after a period of time by using the <xref:System.Threading.CancellationTokenSource.CancelAfter%2A?displayProperty=nameWithType> method if you don't want to wait for the operation to finish. This method schedules the cancellation of any associated tasks that aren't complete within the period of time that's designated by the `CancelAfter` expression.
@ -56,7 +55,7 @@ static async Task Main()
}
```
The updated `Main` method writes a few instructional messages to the console. Within the [try catch](../../../language-reference/keywords/try-catch.md), a call to <xref:System.Threading.CancellationTokenSource.CancelAfter(System.Int32)?displayProperty=nameWithType> schedules a cancellation. This will signal cancellation after a period of time.
The updated `Main` method writes a few instructional messages to the console. Within the [try catch](../language-reference/keywords/try-catch.md), a call to <xref:System.Threading.CancellationTokenSource.CancelAfter(System.Int32)?displayProperty=nameWithType> schedules a cancellation. This will signal cancellation after a period of time.
Next, the `SumPageSizesAsync` method is awaited. If processing all of the URLs occurs faster than the scheduled cancellation, the application ends. However, if the scheduled cancellation is triggered before all of the URLs are processed, a <xref:System.OperationCanceledException> is thrown.
@ -79,7 +78,7 @@ Application ending.
The following code is the complete text of the *Program.cs* file for the example.
:::code language="csharp" source="snippets/cancel-tasks/cancel-task-after-period-of-time/Program.cs":::
:::code language="csharp" source="snippets/cancel-task-after-period-of-time/Program.cs":::
## See also

Просмотреть файл

@ -146,3 +146,5 @@ Run the application again. Contrast its behavior with the behavior of the starte
You can see improvements in memory use by examining the code. You no longer need to allocate a collection to store all the results before they're enumerated. The caller can determine how to consume the results and if a storage collection is needed.
Run both the starter and finished applications and you can observe the differences between the implementations for yourself. You can delete the GitHub access token you created when you started this tutorial after you've finished. If an attacker gained access to that token, they could access GitHub APIs using your credentials.
In this tutorial, you used async streams to read a individual items from a network API that returns pages of data. Async streams can also read from "never ending streams" like a stock ticker, or sensor device. The call to `MoveNextAsync` returns the next item as soon as it's available.

Просмотреть файл

@ -1,8 +1,7 @@
---
title: Asynchronous programming in C#
description: An overview of the C# language support for asynchronous programming using async, await, Task, and Task<T>
ms.date: 05/17/2022
recommendations: false
ms.date: 02/08/2023
---
# Asynchronous programming with async and await
@ -93,7 +92,7 @@ Console.WriteLine("Oj is ready");
Console.WriteLine("Breakfast is ready!");
```
Next, you can move the `await` statements for the bacon and eggs to the end of the method, before serving breakfast:
The preceding code won't get your breakfast ready any faster. The tasks are all `await`ed as soon as they are started. Next, you can move the `await` statements for the bacon and eggs to the end of the method, before serving breakfast:
```csharp
Coffee cup = PourCoffee();
@ -246,6 +245,8 @@ while (breakfastTasks.Count > 0)
}
```
Near the end, you see the line `await finishedTask;`. The line `await Task.WhenAny` doesn't await the finished task. It `await`s the `Task` returned by `Task.WhenAny`. The result of `Task.WhenAny` is the task that has completed (or faulted). You should `await` that task again, even though you know it's finished running. That's how you retrieve its result, or ensure that the exception causing it to fault gets thrown.
After all those changes, the final version of the code looks like this:
<a id="final-version"></a>
:::code language="csharp" source="snippets/index/AsyncBreakfast-final/Program.cs" highlight="16-47":::
@ -259,4 +260,4 @@ This final code is asynchronous. It more accurately reflects how a person would
## Next steps
> [!div class="nextstepaction"]
> [Explore real world scenarios for asynchronous programs](../../../async.md)
> [Explore real world scenarios for asynchronous programs](async-scenarios.md)

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 49 KiB

После

Ширина:  |  Высота:  |  Размер: 49 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 20 KiB

После

Ширина:  |  Высота:  |  Размер: 20 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 21 KiB

После

Ширина:  |  Высота:  |  Размер: 21 KiB

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>access_web</RootNamespace>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<StartupObject>AsyncExamples.Program</StartupObject>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>cancel_task_after_period_of_time</RootNamespace>

Просмотреть файл

@ -50,7 +50,20 @@ class Program
Task sumPageSizesTask = SumPageSizesAsync();
await Task.WhenAny(new[] { cancelTask, sumPageSizesTask });
Task finishedTask = await Task.WhenAny(new[] { cancelTask, sumPageSizesTask });
if (finishedTask == cancelTask)
{
// wait for the cancellation to take place:
try
{
await sumPageSizesTask;
Console.WriteLine("Download task completed before cancel request was processed.");
}
catch (TaskCanceledException)
{
Console.WriteLine("Download task has been cancelled.");
}
}
Console.WriteLine("Application ending.");
}

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>cancel_tasks</RootNamespace>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>file_access</RootNamespace>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Просмотреть файл

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

Просмотреть файл

@ -1,7 +1,7 @@
---
title: Process asynchronous tasks as they complete
description: Learn how to use Task.WhenAny in C# to start multiple tasks and process their results as they finish, rather than process them in the order started.
ms.date: 10/27/2021
ms.date: 02/08/2023
zone_pivot_groups: dotnet-version
ms.topic: tutorial
---
@ -18,12 +18,12 @@ The following example uses a query to create a collection of tasks. Each task do
You can follow this tutorial by using one of the following options:
* [Visual Studio 2022 version 17.0.0 Preview](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=learn.microsoft.com&utm_campaign=inline+link&utm_content=download+vs2022) with the **.NET desktop development** workload installed. The .NET 6.0 SDK is automatically installed when you select this workload.
* The [.NET 6.0 SDK](https://dotnet.microsoft.com/download/dotnet/6.0) with a code editor of your choice, such as [Visual Studio Code](https://code.visualstudio.com/).
* [Visual Studio 2022](https://visualstudio.microsoft.com/downloads) with the **.NET desktop development** workload installed. The .NET SDK is automatically installed when you select this workload.
* The [.NET SDK](https://dotnet.microsoft.com/download/) with a code editor of your choice, such as [Visual Studio Code](https://code.visualstudio.com/).
## Create example application
Create a new .NET Core console application that targets .NET 6.0. You can create one by using the [dotnet new console](../../../../core/tools/dotnet-new-sdk-templates.md#console) command or from Visual Studio.
Create a new .NET Core console application. You can create one by using the [dotnet new console](../../core/tools/dotnet-new-sdk-templates.md#console) command or from Visual Studio.
Open the *Program.cs* file in your code editor, and replace the existing code with this code:
@ -85,7 +85,7 @@ The main entry point into the console application is the `Main` method. Replace
static Task Main() => SumPageSizesAsync();
```
The updated `Main` method is now considered an [Async main](../../../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It is expressed as a call to `SumPageSizesAsync`.
The updated `Main` method is now considered an [Async main](../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It is expressed as a call to `SumPageSizesAsync`.
## Create the asynchronous sum page sizes method
@ -117,7 +117,7 @@ static async Task SumPageSizesAsync()
}
```
The method starts by instantiating and starting a <xref:System.Diagnostics.Stopwatch>. It then includes a query that, when executed, creates a collection of tasks. Each call to `ProcessUrlAsync` in the following code returns a <xref:System.Threading.Tasks.Task%601>, where `TResult` is an integer:
The `while` loop removes one of the tasks in each iteration. After every task has completed, the loop ends. The method starts by instantiating and starting a <xref:System.Diagnostics.Stopwatch>. It then includes a query that, when executed, creates a collection of tasks. Each call to `ProcessUrlAsync` in the following code returns a <xref:System.Threading.Tasks.Task%601>, where `TResult` is an integer:
```csharp
IEnumerable<Task<int>> downloadTasksQuery =
@ -125,7 +125,7 @@ IEnumerable<Task<int>> downloadTasksQuery =
select ProcessUrlAsync(url, s_client);
```
Due to [deferred execution](../../../../standard/linq/deferred-execution-example.md) with the LINQ, you call <xref:System.Linq.Enumerable.ToList%2A?displayProperty=nameWithType> to start each task.
Due to [deferred execution](../../standard/linq/deferred-execution-example.md) with the LINQ, you call <xref:System.Linq.Enumerable.ToList%2A?displayProperty=nameWithType> to start each task.
```csharp
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
@ -200,7 +200,7 @@ You can follow this tutorial by using one of the following options:
## Create example application
Create a new .NET Core console application that targets .NET 5.0 or .NET Core 3.1. You can create one by using the [dotnet new console](../../../../core/tools/dotnet-new-sdk-templates.md#console) command or from Visual Studio. Open the *Program.cs* file in your favorite code editor.
Create a new .NET Core console application that targets .NET 5.0 or .NET Core 3.1. You can create one by using the [dotnet new console](../../core/tools/dotnet-new-sdk-templates.md#console) command or from Visual Studio. Open the *Program.cs* file in your favorite code editor.
### Replace using statements
@ -259,7 +259,7 @@ The main entry point into the console application is the `Main` method. Replace
static Task Main() => SumPageSizesAsync();
```
The updated `Main` method is now considered an [Async main](../../../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It is expressed a call to `SumPageSizesAsync`.
The updated `Main` method is now considered an [Async main](../fundamentals/program-structure/main-command-line.md#async-main-return-values), which allows for an asynchronous entry point into the executable. It is expressed a call to `SumPageSizesAsync`.
## Create the asynchronous sum page sizes method
@ -299,7 +299,7 @@ IEnumerable<Task<int>> downloadTasksQuery =
select ProcessUrlAsync(url, s_client);
```
Due to [deferred execution](../../../../standard/linq/deferred-execution-example.md) with the LINQ, you call <xref:System.Linq.Enumerable.ToList%2A?displayProperty=nameWithType> to start each task.
Due to [deferred execution](../../standard/linq/deferred-execution-example.md) with the LINQ, you call <xref:System.Linq.Enumerable.ToList%2A?displayProperty=nameWithType> to start each task.
```csharp
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();

Просмотреть файл

@ -1,8 +1,7 @@
---
title: The Task Asynchronous Programming (TAP) model with async and await (C#)"
title: The Task Asynchronous Programming (TAP) model with async and await"
description: Learn when and how to use Task-based async programming, a simplified approach to asynchronous programming in C#.
ms.date: 03/02/2022
ms.assetid: 9bcf896a-5826-4189-8c1a-3e35fa08243a
ms.date: 02/08/2023
---
# Task asynchronous programming model
@ -24,7 +23,7 @@ The following table shows typical areas where asynchronous programming improves
| Web access | <xref:System.Net.Http.HttpClient> | <xref:Windows.Web.Http.HttpClient?displayProperty=nameWithType> <br> <xref:Windows.Web.Syndication.SyndicationClient> |
| Working with files | <xref:System.Text.Json.JsonSerializer> <br> <xref:System.IO.StreamReader> <br> <xref:System.IO.StreamWriter> <br> <xref:System.Xml.XmlReader> <br> <xref:System.Xml.XmlWriter> | <xref:Windows.Storage.StorageFile> |
| Working with images | | <xref:Windows.Media.Capture.MediaCapture> <br> <xref:Windows.Graphics.Imaging.BitmapEncoder> <br> <xref:Windows.Graphics.Imaging.BitmapDecoder> |
| WCF programming | [Synchronous and Asynchronous Operations](../../../../framework/wcf/synchronous-and-asynchronous-operations.md) | |
| WCF programming | [Synchronous and Asynchronous Operations](../../framework/wcf/synchronous-and-asynchronous-operations.md) | |
Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. If any process is blocked in a synchronous application, all are blocked. Your application stops responding, and you might conclude that it has failed when instead it's just waiting.
@ -34,7 +33,7 @@ The async-based approach adds the equivalent of an automatic transmission to the
## <a name="BKMK_HowtoWriteanAsyncMethod"></a> Async methods are easy to write
The [async](../../../language-reference/keywords/async.md) and [await](../../../language-reference/operators/await.md) keywords in C# are the heart of async programming. By using those two keywords, you can use resources in .NET Framework, .NET Core, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using the `async` keyword are referred to as *async methods*.
The [async](../language-reference/keywords/async.md) and [await](../language-reference/operators/await.md) keywords in C# are the heart of async programming. By using those two keywords, you can use resources in .NET Framework, .NET Core, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using the `async` keyword are referred to as *async methods*.
The following example shows an async method. Almost everything in the code should look familiar to you.
@ -76,7 +75,7 @@ The following characteristics summarize what makes the previous example an async
In async methods, you use the provided keywords and types to indicate what you want to do, and the compiler does the rest, including keeping track of what must happen when control returns to an await point in a suspended method. Some routine processes, such as loops and exception handling, can be difficult to handle in traditional asynchronous code. In an async method, you write these elements much as you would in a synchronous solution, and the problem is solved.
For more information about asynchrony in previous versions of .NET Framework, see [TPL and traditional .NET Framework asynchronous programming](../../../../standard/parallel-programming/tpl-and-traditional-async-programming.md).
For more information about asynchrony in previous versions of .NET Framework, see [TPL and traditional .NET Framework asynchronous programming](../../standard/parallel-programming/tpl-and-traditional-async-programming.md).
## <a name="BKMK_WhatHappensUnderstandinganAsyncMethod"></a> What happens in an async method
@ -128,9 +127,9 @@ The async-based approach to asynchronous programming is preferable to existing a
## <a name="BKMK_AsyncandAwait"></a> async and await
If you specify that a method is an async method by using the [async](../../../language-reference/keywords/async.md) modifier, you enable the following two capabilities.
If you specify that a method is an async method by using the [async](../language-reference/keywords/async.md) modifier, you enable the following two capabilities.
- The marked async method can use [await](../../../language-reference/operators/await.md) to designate suspension points. The `await` operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.
- The marked async method can use [await](../language-reference/operators/await.md) to designate suspension points. The `await` operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.
The suspension of an async method at an `await` expression doesn't constitute an exit from the method, and `finally` blocks don't run.
@ -140,14 +139,14 @@ An async method typically contains one or more occurrences of an `await` operato
`async` and `await` are contextual keywords. For more information and examples, see the following topics:
- [async](../../../language-reference/keywords/async.md)
- [await](../../../language-reference/operators/await.md)
- [async](../language-reference/keywords/async.md)
- [await](../language-reference/operators/await.md)
## <a name="BKMK_ReturnTypesandParameters"></a> Return types and parameters
An async method typically returns a <xref:System.Threading.Tasks.Task> or a <xref:System.Threading.Tasks.Task%601>. Inside an async method, an `await` operator is applied to a task that's returned from a call to another async method.
You specify <xref:System.Threading.Tasks.Task%601> as the return type if the method contains a [`return`](../../../language-reference/statements/jump-statements.md#the-return-statement) statement that specifies an operand of type `TResult`.
You specify <xref:System.Threading.Tasks.Task%601> as the return type if the method contains a [`return`](../language-reference/statements/jump-statements.md#the-return-statement) statement that specifies an operand of type `TResult`.
You use <xref:System.Threading.Tasks.Task> as the return type if the method has no return statement or has a return statement that doesn't return an operand.
@ -188,9 +187,9 @@ An async method can also have a `void` return type. This return type is used pri
An async method that has a `void` return type can't be awaited, and the caller of a void-returning method can't catch any exceptions that the method throws.
An async method can't declare [in](../../../language-reference/keywords/in-parameter-modifier.md), [ref](../../../language-reference/keywords/ref.md) or [out](../../../language-reference/keywords/out-parameter-modifier.md) parameters, but the method can call methods that have such parameters. Similarly, an async method can't return a value by reference, although it can call methods with ref return values.
An async method can't declare [in](../language-reference/keywords/in-parameter-modifier.md), [ref](../language-reference/keywords/ref.md) or [out](../language-reference/keywords/out-parameter-modifier.md) parameters, but the method can call methods that have such parameters. Similarly, an async method can't return a value by reference, although it can call methods with ref return values.
For more information and examples, see [Async return types (C#)](async-return-types.md). For more information about how to catch exceptions in async methods, see [try-catch](../../../language-reference/keywords/try-catch.md).
For more information and examples, see [Async return types (C#)](async-return-types.md). For more information about how to catch exceptions in async methods, see [try-catch](../language-reference/keywords/try-catch.md).
Asynchronous APIs in Windows Runtime programming have one of the following return types, which are similar to tasks:
@ -213,11 +212,11 @@ You can ignore the convention where an event, base class, or interface contract
| [Async return types (C#)](async-return-types.md) | Illustrates the types that async methods can return, and explains when each type is appropriate. |
| Cancel tasks with a cancellation token as a signaling mechanism. | Shows how to add the following functionality to your async solution:<br><br> - [Cancel a list of tasks (C#)](cancel-an-async-task-or-a-list-of-tasks.md)<br>- [Cancel tasks after a period of time (C#)](cancel-async-tasks-after-a-period-of-time.md)<br>- [Process asynchronous task as they complete (C#)](start-multiple-async-tasks-and-process-them-as-they-complete.md) |
| [Using async for file access (C#)](using-async-for-file-access.md) | Lists and demonstrates the benefits of using async and await to access files. |
| [Task-based asynchronous pattern (TAP)](../../../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) | Describes an asynchronous pattern, the pattern is based on the <xref:System.Threading.Tasks.Task> and <xref:System.Threading.Tasks.Task%601> types. |
| [Task-based asynchronous pattern (TAP)](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) | Describes an asynchronous pattern, the pattern is based on the <xref:System.Threading.Tasks.Task> and <xref:System.Threading.Tasks.Task%601> types. |
| [Async Videos on Channel 9](/shows/browse?terms=async) | Provides links to a variety of videos about async programming. |
## See also
- [Asynchronous programming with async and await](index.md)
- [async](../../../language-reference/keywords/async.md)
- [await](../../../language-reference/operators/await.md)
- [async](../language-reference/keywords/async.md)
- [await](../language-reference/operators/await.md)

Просмотреть файл

@ -1,9 +1,8 @@
---
title: Asynchronous file access (C#)
description: Learn how to use the async feature to access files in C#. You can call into asynchronous methods without using callbacks or splitting your code across methods.
ms.date: 08/19/2020
ms.date: 02/08/2023
ms.topic: tutorial
ms.assetid: bb018fea-5313-4c80-ab3f-7c24b2145bd9
---
# Asynchronous file access (C#)
@ -79,7 +78,7 @@ Any performance boost is almost entirely from the parallel processing and not th
:::code language="csharp" source="snippets/file-access/Program.cs" id="ParallelWriteText":::
When using the <xref:System.IO.Stream.WriteAsync%2A> and <xref:System.IO.Stream.ReadAsync%2A> methods, you can specify a <xref:System.Threading.CancellationToken>, which you can use to cancel the operation mid-stream. For more information, see [Cancellation in managed threads](../../../../standard/threading/cancellation-in-managed-threads.md).
When using the <xref:System.IO.Stream.WriteAsync%2A> and <xref:System.IO.Stream.ReadAsync%2A> methods, you can specify a <xref:System.Threading.CancellationToken>, which you can use to cancel the operation mid-stream. For more information, see [Cancellation in managed threads](../../standard/threading/cancellation-in-managed-threads.md).
## See also

Просмотреть файл

@ -121,8 +121,8 @@ and work with different data sources.
Modern programs often use asynchronous operations. These articles will help you learn
to use these techniques.
- [Improve async performance using `System.Threading.Tasks.Task.WhenAll`](../programming-guide/concepts/async/index.md).
- [Make multiple web requests in parallel using `async` and `await`](../programming-guide/concepts/async/index.md).
- [Improve async performance using `System.Threading.Tasks.Task.WhenAll`](../asynchronous-programming/async-scenarios.md).
- [Make multiple web requests in parallel using `async` and `await`](../asynchronous-programming/async-scenarios.md).
- [Use a thread pool](../../standard/threading/the-managed-thread-pool.md#using-the-thread-pool).
## Command line args to your program

Просмотреть файл

@ -170,4 +170,4 @@ The expected output appears at the end of the code.
## See also
- [await](../operators/await.md)
- [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md)
- [Asynchronous programming with async and await](../../asynchronous-programming/index.md)

Просмотреть файл

@ -22,7 +22,7 @@ public async Task<int> ExampleMethodAsync()
}
```
If you're new to asynchronous programming or do not understand how an async method uses the [`await` operator](../operators/await.md) to do potentially long-running work without blocking the caller's thread, read the introduction in [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md). The following code is found inside an async method and calls the <xref:System.Net.Http.HttpClient.GetStringAsync%2a?displayProperty=nameWithType> method:
If you're new to asynchronous programming or do not understand how an async method uses the [`await` operator](../operators/await.md) to do potentially long-running work without blocking the caller's thread, read the introduction in [Asynchronous programming with async and await](../../asynchronous-programming/index.md). The following code is found inside an async method and calls the <xref:System.Net.Http.HttpClient.GetStringAsync%2a?displayProperty=nameWithType> method:
```csharp
string contents = await httpClient.GetStringAsync(requestUrl);
@ -61,7 +61,7 @@ To run the code as a Windows Store app:
[!code-csharp[wpf-async](../../../../samples/snippets/csharp/language-reference/keywords/async/wpf/MainWindow.xaml.cs#1)]
> [!IMPORTANT]
> For more information about tasks and the code that executes while waiting for a task, see [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md). For a full console example that uses similar elements, see [Process asynchronous tasks as they complete (C#)](../../programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md).
> For more information about tasks and the code that executes while waiting for a task, see [Asynchronous programming with async and await](../../asynchronous-programming/index.md). For a full console example that uses similar elements, see [Process asynchronous tasks as they complete (C#)](../../asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete.md).
## Return Types
@ -80,11 +80,11 @@ You use the `void` return type primarily to define event handlers, which require
You return another type, typically a value type, that has a `GetAwaiter` method to minimize memory allocations in performance-critical sections of code.
For more information and examples, see [Async Return Types](../../programming-guide/concepts/async/async-return-types.md).
For more information and examples, see [Async Return Types](../../asynchronous-programming/async-return-types.md).
## See also
- <xref:System.Runtime.CompilerServices.AsyncStateMachineAttribute>
- [await](../operators/await.md)
- [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md)
- [Process asynchronous tasks as they complete](../../programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md)
- [Asynchronous programming with async and await](../../asynchronous-programming/index.md)
- [Process asynchronous tasks as they complete](../../asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete.md)

Просмотреть файл

@ -128,7 +128,7 @@ For more information about catch, see [try-catch-finally](try-catch-finally.md).
An async method is marked by an [async](async.md) modifier and usually contains one or more await expressions or statements. An await expression applies the [await](../operators/await.md) operator to a <xref:System.Threading.Tasks.Task> or <xref:System.Threading.Tasks.Task%601>.
When control reaches an `await` in the async method, progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method. For more information, see [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md).
When control reaches an `await` in the async method, progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method. For more information, see [Asynchronous programming with async and await](../../asynchronous-programming/index.md).
The completed task to which `await` is applied might be in a faulted state because of an unhandled exception in the method that returns the task. Awaiting the task throws an exception. A task can also end up in a canceled state if the asynchronous process that returns it is canceled. Awaiting a canceled task throws an `OperationCanceledException`.

Просмотреть файл

@ -19,7 +19,7 @@ In the following example, the <xref:System.Net.Http.HttpClient.GetByteArrayAsync
The preceding example uses the [async `Main` method](../../fundamentals/program-structure/main-command-line.md). For more information, see the [await operator in the Main method](#await-operator-in-the-main-method) section.
> [!NOTE]
> For an introduction to asynchronous programming, see [Asynchronous programming with async and await](../../programming-guide/concepts/async/index.md). Asynchronous programming with `async` and `await` follows the [task-based asynchronous pattern](../../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md).
> For an introduction to asynchronous programming, see [Asynchronous programming with async and await](../../asynchronous-programming/index.md). Asynchronous programming with `async` and `await` follows the [task-based asynchronous pattern](../../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md).
You can use the `await` operator only in a method, [lambda expression](lambda-expressions.md), or [anonymous method](delegate-operator.md) that is modified by the [async](../keywords/async.md) keyword. Within an async method, you can't use the `await` operator in the body of a synchronous function, inside the block of a [lock statement](../statements/lock.md), and in an [unsafe](../keywords/unsafe.md) context.
@ -46,7 +46,7 @@ For more information, see the [Await expressions](~/_csharpstandard/standard/exp
- [C# reference](../index.md)
- [C# operators and expressions](index.md)
- [async](../keywords/async.md)
- [Task asynchronous programming model](../../programming-guide/concepts/async/task-asynchronous-programming-model.md)
- [Asynchronous programming](../../async.md)
- [Walkthrough: accessing the Web by using async and await](../../programming-guide/concepts/async/index.md)
- [Tutorial: Generate and consume async streams](../../tutorials/generate-consume-asynchronous-stream.md)
- [Task asynchronous programming model](../../asynchronous-programming/task-asynchronous-programming-model.md)
- [Asynchronous programming](../../asynchronous-programming/index.md)
- [Walkthrough: accessing the Web by using async and await](../../asynchronous-programming/async-scenarios.md)
- [Tutorial: Generate and consume async streams](../../asynchronous-programming/generate-consume-asynchronous-stream.md)

Просмотреть файл

@ -144,7 +144,7 @@ public partial class Form1 : Form
}
```
For more information about how to create and use async methods, see [Asynchronous Programming with async and await](../../programming-guide/concepts/async/index.md).
For more information about how to create and use async methods, see [Asynchronous Programming with async and await](../../asynchronous-programming/index.md).
## Lambda expressions and tuples

Просмотреть файл

@ -107,7 +107,7 @@ You can also use the `await foreach` statement with an instance of any type that
- A type has the public parameterless `GetAsyncEnumerator` method. That method can be a type's [extension method](../../programming-guide/classes-and-structs/extension-methods.md).
- The return type of the `GetAsyncEnumerator` method has the public `Current` property and the public parameterless `MoveNextAsync` method whose return type is [`Task<bool>`](xref:System.Threading.Tasks.Task%601), [`ValueTask<bool>`](xref:System.Threading.Tasks.ValueTask%601), or any other awaitable type whose awaiter's `GetResult` method returns a `bool` value.
By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the <xref:System.Threading.Tasks.TaskAsyncEnumerableExtensions.ConfigureAwait%2A?displayProperty=nameWithType> extension method. For more information about synchronization contexts and capturing the current context, see [Consuming the Task-based asynchronous pattern](../../../standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md). For more information about asynchronous streams, see the [Asynchronous streams tutorial](../../tutorials/generate-consume-asynchronous-stream.md).
By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the <xref:System.Threading.Tasks.TaskAsyncEnumerableExtensions.ConfigureAwait%2A?displayProperty=nameWithType> extension method. For more information about synchronization contexts and capturing the current context, see [Consuming the Task-based asynchronous pattern](../../../standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern.md). For more information about asynchronous streams, see the [Asynchronous streams tutorial](../../asynchronous-programming/generate-consume-asynchronous-stream.md).
### Type of an iteration variable

Просмотреть файл

@ -252,7 +252,7 @@ In the following example, `DelayAsync` is an async method that has a return stat
An async method can't declare any [in](language-reference/keywords/in-parameter-modifier.md), [ref](language-reference/keywords/ref.md), or [out](language-reference/keywords/out-parameter-modifier.md) parameters, but it can call methods that have such parameters.
For more information about async methods, see [Asynchronous programming with async and await](async.md) and [Async return types](programming-guide/concepts/async/async-return-types.md).
For more information about async methods, see [Asynchronous programming with async and await](asynchronous-programming/index.md) and [Async return types](asynchronous-programming/async-return-types.md).
<a name="expr"></a>

Просмотреть файл

@ -74,7 +74,7 @@ codebases.
You have one final pattern to learn: How to correctly write event
subscribers that call async code. The challenge is described in
the article on [async and await](async.md). Async methods can
the article on [async and await](asynchronous-programming/index.md). Async methods can
have a void return type, but that is strongly discouraged. When your
event subscriber code calls an async method, you have no choice but
to create an `async void` method. The event handler signature requires

Просмотреть файл

@ -129,7 +129,7 @@ The `Main` method is an example of an async method that has a return type of <xr
An async method can't declare any [ref](../../language-reference/keywords/ref.md) or [out](../../language-reference/keywords/out-parameter-modifier.md) parameters, but it can call methods that have such parameters.
For more information about async methods, see [Asynchronous programming with async and await](../concepts/async/index.md) and [Async return types](../concepts/async/async-return-types.md).
For more information about async methods, see [Asynchronous programming with async and await](../../asynchronous-programming/index.md) and [Async return types](../../asynchronous-programming/async-return-types.md).
## Expression body definitions

Просмотреть файл

@ -12,7 +12,6 @@ This section explains programming concepts in the C# language.
|Title|Description|
|-----------|-----------------|
|[Assemblies in .NET](../../../standard/assembly/index.md)|Describes how to create and use assemblies.|
|[Asynchronous Programming with async and await (C#)](./async/index.md)|Describes how to write asynchronous solutions by using the [async](../../language-reference/keywords/async.md) and [await](../../language-reference/operators/await.md) keywords in C#. Includes a walkthrough.|
|[Attributes (C#)](./attributes/index.md)|Discusses how to provide additional information about programming elements such as types, fields, methods, and properties by using attributes.|
|[Collections (C#)](./collections.md)|Describes some of the types of collections provided by .NET. Demonstrates how to use simple collections and collections of key/value pairs.|
|[Covariance and Contravariance (C#)](./covariance-contravariance/index.md)|Shows how to enable implicit conversion of generic type parameters in interfaces and delegates.|

Просмотреть файл

@ -28,7 +28,7 @@ The following table lists the various types of statements in C# and their associ
|Jump statements|Jump statements transfer control to another section of code. For more information, see the following topics: <ul><li>[break](../../language-reference/statements/jump-statements.md#the-break-statement)</li><li>[continue](../../language-reference/statements/jump-statements.md#the-continue-statement)</li><li>[goto](../../language-reference/statements/jump-statements.md#the-goto-statement)</li><li>[return](../../language-reference/statements/jump-statements.md#the-return-statement)</li><li>[yield](../../language-reference/statements/yield.md)</li></ul>|
|Exception handling statements|Exception handling statements enable you to gracefully recover from exceptional conditions that occur at run time. For more information, see the following topics: <ul><li>[throw](../../language-reference/keywords/throw.md)</li><li>[try-catch](../../language-reference/keywords/try-catch.md)</li><li>[try-finally](../../language-reference/keywords/try-finally.md)</li><li>[try-catch-finally](../../language-reference/keywords/try-catch-finally.md)</li></ul>|
|[`checked` and `unchecked`](../../language-reference/statements/checked-and-unchecked.md)|The `checked` and `unchecked` statements enable you to specify whether integral-type numerical operations are allowed to cause an overflow when the result is stored in a variable that is too small to hold the resulting value.|
|The `await` statement|If you mark a method with the [async](../../language-reference/keywords/async.md) modifier, you can use the [await](../../language-reference/operators/await.md) operator in the method. When control reaches an `await` expression in the async method, control returns to the caller, and progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method.<br /><br /> For a simple example, see the "Async Methods" section of [Methods](../classes-and-structs/methods.md). For more information, see [Asynchronous Programming with async and await](../concepts/async/index.md).|
|The `await` statement|If you mark a method with the [async](../../language-reference/keywords/async.md) modifier, you can use the [await](../../language-reference/operators/await.md) operator in the method. When control reaches an `await` expression in the async method, control returns to the caller, and progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method.<br /><br /> For a simple example, see the "Async Methods" section of [Methods](../classes-and-structs/methods.md). For more information, see [Asynchronous Programming with async and await](../../asynchronous-programming/index.md).|
|The `yield return` statement|An iterator performs a custom iteration over a collection, such as a list or an array. An iterator uses the [yield return](../../language-reference/statements/yield.md) statement to return each element one at a time. When a `yield return` statement is reached, the current location in code is remembered. Execution is restarted from that location when the iterator is called the next time.<br /><br /> For more information, see [Iterators](../concepts/iterators.md).|
|The `fixed` statement|The fixed statement prevents the garbage collector from relocating a movable variable. For more information, see [fixed](../../language-reference/statements/fixed.md).|
|The `lock` statement|The lock statement enables you to limit access to blocks of code to only one thread at a time. For more information, see [lock](../../language-reference/statements/lock.md).|

Просмотреть файл

@ -189,8 +189,6 @@ items:
href: tutorials/ranges-indexes.md
- name: Work with nullable reference types
href: tutorials/nullable-reference-types.md
- name: Generate and consume asynchronous streams
href: tutorials/generate-consume-asynchronous-stream.md
- name: Explore string interpolation - interactive
href: tutorials/exploration/interpolated-strings.yml
- name: Explore string interpolation - in your environment
@ -205,6 +203,28 @@ items:
href: tutorials/working-with-linq.md
- name: Use Attributes
href: tutorials/attributes.md
- name: Asynchronous programming
items:
- name: Overview
displayName: asynchronous programming, async, await
href: asynchronous-programming/index.md
- name: Asynchronous programming scenarios
href: asynchronous-programming/async-scenarios.md
- name: Task asynchronous programming model
href: asynchronous-programming/task-asynchronous-programming-model.md
- name: Async return types
displayName: Task, Task<T>, ValueTask, ValueTask<T>
href: asynchronous-programming/async-return-types.md
- name: Process asynchronous tasks as they complete
href: asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete.md
- name: Asynchronous file access
href: asynchronous-programming/using-async-for-file-access.md
- name: Cancel a list of tasks
href: asynchronous-programming/cancel-an-async-task-or-a-list-of-tasks.md
- name: Cancel tasks after a period of time
href: asynchronous-programming/cancel-async-tasks-after-a-period-of-time.md
- name: Generate and consume asynchronous streams
href: asynchronous-programming/generate-consume-asynchronous-stream.md
- name: C# concepts
items:
- name: Nullable reference types
@ -383,28 +403,6 @@ items:
- name: Overview
displayName: programming concepts
href: programming-guide/concepts/index.md
- name: Asynchronous programming
displayName: async, await, asynchronous programming, task, cancellation
items:
- name: Overview
displayName: asynchronous programming
href: programming-guide/concepts/async/index.md
- name: Asynchronous programming scenarios
href: async.md
- name: Task asynchronous programming model
href: programming-guide/concepts/async/task-asynchronous-programming-model.md
- name: Async return types
href: programming-guide/concepts/async/async-return-types.md
- name: Cancel tasks
items:
- name: Cancel a list of tasks
href: programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks.md
- name: Cancel tasks after a period of time
href: programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md
- name: Process asynchronous tasks as they complete
href: programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md
- name: Asynchronous file access
href: programming-guide/concepts/async/using-async-for-file-access.md
- name: Attributes
items:
- name: Overview

Просмотреть файл

@ -10,7 +10,7 @@ C# (pronounced "See Sharp") is a modern, object-oriented, and type-safe programm
C# is an object-oriented, ***component-oriented*** programming language. C# provides language constructs to directly support these concepts, making C# a natural language in which to create and use software components. Since its origin, C# has added features to support new workloads and emerging software design practices. At its core, C# is an ***object-oriented*** language. You define types and their behavior.
Several C# features help create robust and durable applications. [***Garbage collection***](../../standard/garbage-collection/index.md) automatically reclaims memory occupied by unreachable unused objects. [***Nullable types***](../nullable-references.md) guard against variables that don't refer to allocated objects. [***Exception handling***](../fundamentals/exceptions/index.md) provides a structured and extensible approach to error detection and recovery. [***Lambda expressions***](../language-reference/operators/lambda-expressions.md) support functional programming techniques. [***Language Integrated Query (LINQ)***](../linq/index.md) syntax creates a common pattern for working with data from any source. Language support for [***asynchronous operations***](../programming-guide/concepts/async/index.md) provides syntax for building distributed systems. C# has a [***unified type system***](../fundamentals/types/index.md). All C# types, including primitive types such as `int` and `double`, inherit from a single root `object` type. All types share a set of common operations. Values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C# supports both user-defined [reference types](../language-reference/builtin-types/reference-types.md) and [value types](../language-reference/builtin-types/value-types.md). C# allows dynamic allocation of objects and in-line storage of lightweight structures. C# supports generic methods and types, which provide increased type safety and performance. C# provides iterators, which enable implementers of collection classes to define custom behaviors for client code.
Several C# features help create robust and durable applications. [***Garbage collection***](../../standard/garbage-collection/index.md) automatically reclaims memory occupied by unreachable unused objects. [***Nullable types***](../nullable-references.md) guard against variables that don't refer to allocated objects. [***Exception handling***](../fundamentals/exceptions/index.md) provides a structured and extensible approach to error detection and recovery. [***Lambda expressions***](../language-reference/operators/lambda-expressions.md) support functional programming techniques. [***Language Integrated Query (LINQ)***](../linq/index.md) syntax creates a common pattern for working with data from any source. Language support for [***asynchronous operations***](../asynchronous-programming/index.md) provides syntax for building distributed systems. C# has a [***unified type system***](../fundamentals/types/index.md). All C# types, including primitive types such as `int` and `double`, inherit from a single root `object` type. All types share a set of common operations. Values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C# supports both user-defined [reference types](../language-reference/builtin-types/reference-types.md) and [value types](../language-reference/builtin-types/value-types.md). C# allows dynamic allocation of objects and in-line storage of lightweight structures. C# supports generic methods and types, which provide increased type safety and performance. C# provides iterators, which enable implementers of collection classes to define custom behaviors for client code.
C# emphasizes ***versioning*** to ensure programs and libraries can evolve over time in a compatible manner. Aspects of C#'s design that were directly influenced by versioning considerations include the separate `virtual` and `override` modifiers, the rules for method overload resolution, and support for explicit interface member declarations.

Просмотреть файл

@ -296,4 +296,4 @@ await RunTeleprompter();
This tutorial showed you a number of the features around the C# language and the .NET Core libraries related to working in Console applications. You can build on this knowledge to explore more about the language, and the classes introduced here. You've seen the basics of File and Console I/O, blocking and non-blocking use of the Task-based asynchronous programming, a tour of the C# language and how C# programs are organized, and the .NET CLI.
For more information about File I/O, see [File and Stream I/O](../../standard/io/index.md). For more information about asynchronous programming model used in this tutorial, see [Task-based Asynchronous Programming](../../standard/parallel-programming/task-based-asynchronous-programming.md) and [Asynchronous programming](../async.md).
For more information about File I/O, see [File and Stream I/O](../../standard/io/index.md). For more information about asynchronous programming model used in this tutorial, see [Task-based Asynchronous Programming](../../standard/parallel-programming/task-based-asynchronous-programming.md) and [Asynchronous programming](../asynchronous-programming/index.md).

Просмотреть файл

@ -276,7 +276,7 @@ They did one other thing along with this version, though it's not a traditional
C# version 5.0, released with Visual Studio 2012, was a focused version of the language. Nearly all of the effort for that version went into another groundbreaking language concept: the `async` and `await` model for asynchronous programming. Here's the major features list:
- [Asynchronous members](../async.md)
- [Asynchronous members](../asynchronous-programming/index.md)
- [Caller info attributes](../language-reference/attributes/caller-information.md)
- [Code Project: Caller Info Attributes in C# 5.0](https://www.codeproject.com/Tips/606379/Caller-Info-Attributes-in-Csharp)

Просмотреть файл

@ -30,7 +30,7 @@ The new asynchronous programming feature provides a simple technique to make cod
For more information about the asynchronous programming feature that was introduced in .NET Framework 4.5, see:
- [Asynchronous programming in C#](../../../csharp/async.md)
- [Asynchronous programming in C#](../../../csharp/asynchronous-programming/index.md)
- [Asynchronous Programming with Async and Await (Visual Basic)](../../../visual-basic/programming-guide/concepts/async/index.md)

Просмотреть файл

@ -368,7 +368,7 @@ public Symbol FindMatchingSymbol(string name)
### Async method caching
The next example shows a common problem when you try to use cached results in an [async](../../csharp/programming-guide/concepts/async/index.md) method.
The next example shows a common problem when you try to use cached results in an [async](../../csharp/asynchronous-programming/index.md) method.
**Example 6: caching in async methods**

Просмотреть файл

@ -330,7 +330,7 @@ What to watch out for:
### Interoperate with .NET
If using `async { }` programming, you may need to interoperate with a .NET library or C# codebase that uses [async/await](../../csharp/programming-guide/concepts/async/index.md)-style asynchronous programming. Because C# and the majority of .NET libraries use the <xref:System.Threading.Tasks.Task%601> and <xref:System.Threading.Tasks.Task> types as their core abstractions this may change how you write your F# asynchronous code.
If using `async { }` programming, you may need to interoperate with a .NET library or C# codebase that uses [async/await](../../csharp/language-reference/keywords/async.md)-style asynchronous programming. Because C# and the majority of .NET libraries use the <xref:System.Threading.Tasks.Task%601> and <xref:System.Threading.Tasks.Task> types as their core abstractions this may change how you write your F# asynchronous code.
One option is to switch to writing .NET tasks directly using `task { }`. Alternatively, you can use the `Async.AwaitTask` function to await a .NET asynchronous computation:

Просмотреть файл

@ -144,7 +144,7 @@ IPlayerGrain player = client.GetGrain<IPlayerGrain>(playerId);
### Grain method invocation
The Orleans programming model is based on [asynchronous programming](../../csharp/async.md). Using the grain reference from the previous example, here's how to perform a grain method invocation:
The Orleans programming model is based on [asynchronous programming](../../csharp/asynchronous-programming/index.md). Using the grain reference from the previous example, here's how to perform a grain method invocation:
```csharp
// Invoking a grain method asynchronously

Просмотреть файл

@ -61,6 +61,6 @@ public class MyClass
## See also
- [C# - Asynchronous programming with async and await](../../csharp/programming-guide/concepts/async/index.md)
- [C# - Asynchronous programming with async and await](../../csharp/asynchronous-programming/index.md)
- [Visual Basic - Asynchronous Programming with Async and Await](../../visual-basic/programming-guide/concepts/async/index.md)
- [F# - Asynchronous Programming](../../fsharp/tutorials/async.md)

Просмотреть файл

@ -32,7 +32,7 @@ C# and Visual Basic each have two keywords for asynchronous programming:
- `Await` (Visual Basic) or `await` (C#) operator, which is applied to the result of an async method.
To implement asynchronous I/O operations, use these keywords in conjunction with the async methods, as shown in the following examples. For more information, see [Asynchronous programming with async and await (C#)](../../csharp/programming-guide/concepts/async/index.md) or [Asynchronous Programming with Async and Await (Visual Basic)](../../visual-basic/programming-guide/concepts/async/index.md).
To implement asynchronous I/O operations, use these keywords in conjunction with the async methods, as shown in the following examples. For more information, see [Asynchronous programming with async and await (C#)](../../csharp/asynchronous-programming/index.md) or [Asynchronous Programming with Async and Await (Visual Basic)](../../visual-basic/programming-guide/concepts/async/index.md).
The following example demonstrates how to use two <xref:System.IO.FileStream> objects to copy files asynchronously from one directory to another. Notice that the <xref:System.Web.UI.WebControls.Button.Click> event handler for the <xref:System.Windows.Controls.Button> control is marked with the `async` modifier because it calls an asynchronous method.
@ -55,5 +55,5 @@ The next example shows the code-behind file and the XAML file that are used to o
- <xref:System.IO.Stream>
- [File and Stream I/O](index.md)
- [Asynchronous programming with async and await (C#)](../../csharp/programming-guide/concepts/async/index.md)
- [Asynchronous programming with async and await (C#)](../../csharp/asynchronous-programming/index.md)
- [Asynchronous Programming with Async and Await (Visual Basic)](../../visual-basic/programming-guide/concepts/async/index.md)

Просмотреть файл

@ -251,7 +251,7 @@ To run the project, perform the following steps:
The first two display lines trace the path as `startButton_Click` calls `AccessTheWebAsync`, and `AccessTheWebAsync` calls the asynchronous <xref:System.Net.Http.HttpClient> method <xref:System.Net.Http.HttpClient.GetStringAsync%28System.String%29>. The following image outlines the calls from method to method.
![Steps ONE and TWO](../../../../csharp/programming-guide/concepts/async/media/asynctrace-onetwo.png "AsyncTrace-ONETWO")
![Steps ONE and TWO](./media/control-flow-in-async-programs/asynctrace-onetwo.png "AsyncTrace-ONETWO")
The return type of both `AccessTheWebAsync` and `client.GetStringAsync` is <xref:System.Threading.Tasks.Task%601>. For `AccessTheWebAsync`, TResult is an integer. For `GetStringAsync`, TResult is a string. For more information about async method return types, see [Async Return Types (Visual Basic)](async-return-types.md).
@ -283,7 +283,7 @@ Dim urlContents As String = Await getStringTask
The following image shows the flow of control from `client.GetStringAsync` to the assignment to `getStringTask` and from the creation of `getStringTask` to the application of an Await operator.
![Step THREE](../../../../csharp/programming-guide/concepts/async/media/asynctrace-three.png "AsyncTrace-Three")
![Step THREE](./media/control-flow-in-async-programs/asynctrace-three.png "AsyncTrace-Three")
The await expression suspends `AccessTheWebAsync` until `client.GetStringAsync` returns. In the meantime, control returns to the caller of `AccessTheWebAsync`, `startButton_Click`.
@ -318,7 +318,7 @@ Dim contentLength As Integer = Await getLengthTask
In the following illustration, the arrows show the flow of control from the await expression in `AccessTheWebAsync` to the assignment of a value to `getLengthTask`, followed by normal processing in `startButton_Click` until `getLengthTask` is awaited.
![Step FOUR](../../../../csharp/programming-guide/concepts/async/media/asynctrace-four.png "AsyncTrace-FOUR")
![Step FOUR](./media/control-flow-in-async-programs/asynctrace-four.png "AsyncTrace-FOUR")
### Step FIVE
@ -335,7 +335,7 @@ The operand of the return statement, `urlContents.Length`, is stored in the task
The following image shows the transfer of control after `client.GetStringAsync` (and `getStringTask`) are complete.
![Step FIVE](../../../../csharp/programming-guide/concepts/async/media/asynctrace-five.png "AsyncTrace-FIVE")
![Step FIVE](./media/control-flow-in-async-programs/asynctrace-five.png "AsyncTrace-FIVE")
`AccessTheWebAsync` runs to completion, and control returns to `startButton_Click`, which is awaiting the completion.
@ -360,7 +360,7 @@ Dim contentLength As Integer = Await getLengthTask
The following image shows the return of control from `AccessTheWebAsync` to `startButton_Click`.
![Step SIX](../../../../csharp/programming-guide/concepts/async/media/asynctrace-six.png "AsyncTrace-SIX")
![Step SIX](./media/control-flow-in-async-programs/asynctrace-six.png "AsyncTrace-SIX")
## See also

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 19 KiB

После

Ширина:  |  Высота:  |  Размер: 19 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 19 KiB

После

Ширина:  |  Высота:  |  Размер: 19 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 14 KiB

После

Ширина:  |  Высота:  |  Размер: 14 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 18 KiB

После

Ширина:  |  Высота:  |  Размер: 18 KiB

Просмотреть файл

До

Ширина:  |  Высота:  |  Размер: 12 KiB

После

Ширина:  |  Высота:  |  Размер: 12 KiB