Обзор поддержки асинхронного выполненияAsync Support Overview
В C# 5 появились два ключевых слова для упрощения асинхронной программы: async и await. Эти ключевые слова позволяют написать простой код, использующий библиотеку параллельных задач для выполнения длительных операций (таких как сетевой доступ) в другом потоке и простого доступа к результатам по завершении. Последние версии Xamarin. iOS и Xamarin. Android поддерживают Async и await — этот документ содержит объяснения и пример использования нового синтаксиса с Xamarin.C# 5 introduced two keywords to simplify asynchronous programing: async and await. These keywords let you write simple code that utilizes the Task Parallel Library to execute long running operations (such as network access) in another thread and easily access the results on completion. The latest versions of Xamarin.iOS and Xamarin.Android support async and await - this document provides explanations and an example of using the new syntax with Xamarin.
Поддержка асинхронной работы Xamarin основана на моно 3,0 Foundation и обновляет профиль API с помощью совместимой с мобильными версиями Silverlight, которая является удобной для мобильных устройств версией .NET 4,5.Xamarin's Async support is built on the Mono 3.0 foundation and upgrades the API profile from the being a Mobile-friendly version of Silverlight to be a mobile-friendly version of .NET 4.5.
ОбзорOverview
В этом документе представлены новые ключевые слова Async и await, а затем приведены некоторые простые примеры реализации асинхронных методов в Xamarin. iOS и Xamarin. Android.This document introduces the new async and await keywords then walks through some simple examples implementing asynchronous methods in Xamarin.iOS and Xamarin.Android.
Более подробное обсуждение новых асинхронных функций C# 5 (включая множество примеров и различных сценариев использования) см. в статье Асинхронное программирование.For a more complete discussion of the new asynchronous features of C# 5 (including lots of samples and different usage scenarios) refer to the article Asynchronous programming.
Пример приложения выполняет простой асинхронный веб-запрос (без блокировки основного потока), а затем обновляет пользовательский интерфейс с загруженным кодом HTML и числом символов.The sample application makes a simple asynchronous web request (without blocking the main thread) then updates the UI with the downloaded html and character count.
Поддержка асинхронной работы Xamarin основана на моно 3,0 Foundation и обновляет профиль API с помощью совместимой с мобильными версиями Silverlight, которая является удобной для мобильных устройств версией .NET 4,5.Xamarin's async support is built on the Mono 3.0 foundation and upgrades the API profile from the being a mobile-friendly version of Silverlight to be a mobile-friendly version of .NET 4.5.
ТребованияRequirements
Для компонентов C# 5 требуется моно 3,0, включенный в Xamarin. iOS 6,4 и Xamarin. Android 4,8.C# 5 features require Mono 3.0 that is included in Xamarin.iOS 6.4 and Xamarin.Android 4.8. Вам будет предложено обновить Mono, Xamarin. iOS, Xamarin. Android и Xamarin. Mac, чтобы воспользоваться его преимуществами.You will be prompted to upgrade your Mono, Xamarin.iOS, Xamarin.Android and Xamarin.Mac to take advantage of it.
Использование Async & awaitUsing async & await
async
и await
являются новыми функциями языка C#, которые работают совместно с библиотекой параллельных задач, чтобы упростить написание потокового кода для выполнения длительных задач без блокировки основного потока приложения.async
and await
are new C# language features that work in conjunction with the Task Parallel Library to make it easy to write threaded code to perform long-running tasks without blocking the main thread of your application.
asyncasync
ОбъявлениеDeclaration
async
Ключевое слово помещается в объявление метода (или в лямбда-или анонимном методе), чтобы указать, что он содержит код, который может выполняться асинхронно, IE. не блокируйте поток вызывающего объекта.The async
keyword is placed in a method declaration (or on a lambda or anonymous method) to indicate that it contains code that can run asynchronously, ie. not block the caller’s thread.
Метод, помеченный как, async
должен содержать по крайней мере одно выражение или оператор await.A method marked with async
should contain at least one await expression or statement. Если await
в методе отсутствуют операторы, они будут выполняться синхронно (то же, что и при отсутствии async
модификатора).If no await
statements are present in the method then it will run synchronously (the same as if there were no async
modifier). Это также приведет к появлению предупреждения компилятора (но не ошибки).This will also result in a compiler warning (but not an error).
Типы возвращаемых данныхReturn Types
Асинхронный метод должен возвращать Task
, Task<TResult>
или void
.An async method should return a Task
, Task<TResult>
or void
.
Укажите Task
тип возвращаемого значения, если метод не возвращает никаких других значений.Specify the Task
return type if the method does not return any other value.
Укажите Task<TResult>
, должен ли метод возвращать значение, где TResult
— возвращаемый тип (например int
,).Specify Task<TResult>
if the method needs to return a value, where TResult
is the type being returned (such as an int
, for example).
void
Тип возвращаемого значения используется главным образом для обработчиков событий, которым он необходим.The void
return type is used mainly for event handlers which require it. Код, вызывающий асинхронные методы, возвращающие значение void, не может быть await
получен в результате.Code that calls void-returning asynchronous methods can’t await
on the result.
ПараметрыParameters
Асинхронные методы не могут объявлять ref
out
Параметры или.Asynchronous methods cannot declare ref
or out
parameters.
awaitawait
Оператор await можно применить к задаче внутри метода, помеченного как async.The await operator can be applied to a Task inside a method marked as async. Это приводит к тому, что метод останавливает выполнение в этой точке и ждет завершения задачи.It causes the method to stop execution at that point and wait until the task completes.
Использование await не блокирует поток вызывающего объекта, а элемент управления возвращается вызывающему.Using await does not block the caller’s thread – rather control is returned to the caller. Это означает, что вызывающий поток не блокируется, поэтому, например, поток пользовательского интерфейса не будет заблокирован при ожидании задачи.This means that the calling thread is not blocked, so for example the user interface thread would not be blocked when awaiting a task.
По завершении задачи метод возобновляет выполнение в той же точке кода.When the task completes, the method resumes executing at the same point in the code. Сюда входит возврат к области try блока try-catch-finally (если таковой имеется).This includes returning to the try scope of a try-catch-finally block (if one is present). await нельзя использовать в блоке catch или finally.await cannot be used in a catch or finally block.
Дополнительные сведения о ожидании в документация Майкрософт.Read more about await on Microsoft Docs.
Обработка исключенийException Handling
Исключения, возникающие в асинхронном методе, сохраняются в задаче и вызываются, когда задача является await
ED.Exceptions that occur inside an async method are stored in the task and thrown when the task is await
ed. Эти исключения могут быть перехвачены и обработаны внутри блока try-catch.These exceptions can be caught and handled inside a try-catch block.
ОтменаCancellation
Асинхронные методы, выполнение которых занимает много времени, должны поддерживать отмену.Asynchronous methods that take a long time to complete should support cancellation. Как правило, отмена вызывается следующим образом:Typically, cancellation is invoked as follows:
CancellationTokenSource
Создается объект.ACancellationTokenSource
object is created.CancellationTokenSource.Token
Экземпляр передается асинхронному методу, допускающему отмену.TheCancellationTokenSource.Token
instance is passed to a cancellable asynchronous method.- Отмена запрашивается путем вызова
CancellationTokenSource.Cancel
метода.Cancellation is requested by calling theCancellationTokenSource.Cancel
method.
Затем задача отменяет саму себя и подтверждает отмену.The task then cancels itself and acknowledges the cancellation.
Дополнительные сведения об отмене см. в разделе Настройка асинхронного приложения (C#).For more information about cancellation, see Fine-Tuning Your Async Application (C#).
ПримерExample
Скачайте пример решения Xamarin (для iOS и Android), чтобы просмотреть рабочий пример async
и await
в мобильных приложениях.Download the example Xamarin solution (for both iOS and Android) to see a working example of async
and await
in mobile apps. Пример кода более подробно рассматривается в этом разделе.The example code is discussed in more detail in this section.
Написание асинхронного методаWriting an async method
Следующий метод демонстрирует создание кода async
метода с помощью await
задачи Ed:The following method demonstrates how to code an async
method with an await
ed task:
public async Task<int> DownloadHomepage()
{
var httpClient = new HttpClient(); // Xamarin supports HttpClient!
Task<string> contentsTask = httpClient.GetStringAsync("https://visualstudio.microsoft.com/xamarin"); // async method!
// await! control returns to the caller and the task continues to run on another thread
string contents = await contentsTask;
ResultEditText.Text += "DownloadHomepage method continues after async call. . . . .\n";
// After contentTask completes, you can calculate the length of the string.
int exampleInt = contents.Length;
ResultEditText.Text += "Downloaded the html and found out the length.\n\n\n";
ResultEditText.Text += contents; // just dump the entire HTML
return exampleInt; // Task<TResult> returns an object of type TResult, in this case int
}
Обратите внимание на следующие моменты:Note these points:
- Объявление метода включает
async
ключевое слово.The method declaration includes theasync
keyword. - Тип возвращаемого значения заключается в том,
Task<int>
что вызывающий код может получить доступ кint
значению, вычисленному в этом методе.The return type isTask<int>
so calling code can access theint
value that is calculated in this method. - Оператор Return представляет собой
return exampleInt;
целочисленный объект — тот факт, что возвращаемый методTask<int>
является частью улучшений языка.The return statement isreturn exampleInt;
which is an integer object – the fact that the method returnsTask<int>
is part of the language improvements.
Вызов асинхронного метода 1Calling an async method 1
Этот обработчик событий нажатия кнопки можно найти в примере приложения Android для вызова описанного выше метода:This button click event handler can be found in the Android sample application to call the method discussed above:
GetButton.Click += async (sender, e) => {
Task<int> sizeTask = DownloadHomepage();
ResultTextView.Text = "loading...";
ResultEditText.Text = "loading...\n";
// await! control returns to the caller
var intResult = await sizeTask;
// when the Task<int> returns, the value is available and we can display on the UI
ResultTextView.Text = "Length: " + intResult ;
// "returns" void, since it's an event handler
};
Примечания.Notes:
- Анонимный делегат имеет префикс ключевого слова Async.The anonymous delegate has the async keyword prefix.
- Асинхронный метод Довнлоадхомепаже возвращает задачу <int> , которая хранится в переменной сизетаск.The asynchronous method DownloadHomepage returns a Task<int> that is stored in the sizeTask variable.
- Код ожидает переменную Сизетаск.The code awaits on the sizeTask variable. Это расположение, в котором метод приостанавливается, и управление возвращается вызывающему коду до тех пор, пока асинхронная задача не завершится в собственном потоке.This is the location that the method is suspended and control is returned to the calling code until the asynchronous task finishes on its own thread.
- Выполнение не приостанавливается при создании задачи в первой строке метода, несмотря на то, что в ней создается задача.Execution does not pause when the task is created on the first line of the method, despite the task being created there. Ключевое слово await обозначает место приостановки выполнения.The await keyword signifies the location where execution is paused.
- По завершении асинхронной задачи устанавливается параметр tResult, и выполнение остается в исходном потоке из строки await.When the asynchronous task finishes, intResult is set and execution continues on the original thread, from the await line.
Вызов асинхронного метода 2Calling an async method 2
В примере приложения iOS пример написан несколько иначе, чтобы продемонстрировать альтернативный подход.In the iOS sample application the example is written slightly differently to demonstrate an alternative approach. Вместо использования анонимного делегата в этом примере объявляется async
обработчик событий, который назначается как обычный обработчик событий:Rather than use an anonymous delegate this example declares an async
event handler that is assigned like a regular event handler:
GetButton.TouchUpInside += HandleTouchUpInside;
Затем метод обработчика событий определяется, как показано ниже:The event handler method is then defined as shown here:
async void HandleTouchUpInside (object sender, EventArgs e)
{
ResultLabel.Text = "loading...";
ResultTextView.Text = "loading...\n";
// await! control returns to the caller
var intResult = await DownloadHomepage();
// when the Task<int> returns, the value is available and we can display on the UI
ResultLabel.Text = "Length: " + intResult ;
}
Некоторые важные моменты:Some important points:
- Метод помечается как,
async
но возвращаетvoid
.The method is marked asasync
but returnsvoid
. Обычно это делается только для обработчиков событий (в противном случае возвращаетсяTask
илиTask<TResult>
).This is typically only done for event handlers (otherwise you’d return aTask
orTask<TResult>
). await
Ключевое слово вDownloadHomepage
методе непосредственно присваивает переменной () вintResult
отличие от предыдущего примера, где мы использовали промежуточнуюTask<int>
переменную для ссылки на задачу.Theawait
keyword on theDownloadHomepage
method directly assigns to a variable (intResult
) unlike the previous example where we used an intermediateTask<int>
variable to reference the task. Это расположение, где управление возвращается вызывающему объекту до тех пор, пока асинхронный метод не завершит работу в другом потоке.This is the location where control is returned to the caller until the asynchronous method has completed on another thread.- Когда асинхронный метод завершает работу и возвращает значение, выполнение возобновляется с,
await
что означает возврат целочисленного результата и последующее его отображение в мини-приложении пользовательского интерфейса.When the asynchronous method completes and returns, execution resumes at theawait
which means the integer result is returned and then rendered in a UI widget.
СводкаSummary
Использование Async и await значительно упрощает код, необходимый для инициирования длительных операций в фоновых потоках, не блокируя основной поток.Using async and await greatly simplifies the code required to spawn long-running operations on background threads without blocking the main thread. Они также упрощают доступ к результатам после завершения задачи.They also make it easy to access the results when the task has completed.
В этом документе представлен обзор новых ключевых слов языка и примеров для Xamarin. iOS и Xamarin. Android.This document has given an overview of the new language keywords and examples for both Xamarin.iOS and Xamarin.Android.
Связанные ссылкиRelated Links
- Асинкаваит (пример)AsyncAwait (sample)
- Обратные вызовы в качестве оператора Go в поколенияхCallbacks as our Generations' Go To Statement
- Данные (iOS) (пример)Data (iOS) (sample)
- HttpClient (iOS) (пример)HttpClient (iOS) (sample)
- Мапкитсеарч (iOS) (пример)MapKitSearch (iOS) (sample)
- Асинхронное программированиеAsynchronous programming
- Fine-Tuning Your Async Application (C#) (Тонкая настройка асинхронного приложения в C#)Fine-Tuning Your Async Application (C#)
- Ожидание, Пользовательский интерфейс и взаимоблокировки! Вот это да!Await, and UI, and deadlocks! Oh my!
- Обработка задач по мере их завершения)Processing tasks as they complete)
- Task-based Asynchronous Pattern (TAP) (Асинхронный шаблон, основанный на задачах (TAP))Task-based Asynchronous Pattern (TAP)
- Асинхронность в C# 5 (блог «Липперта») — о вводе ключевых словAsynchrony in C# 5 (Eric Lippert's blog) – about the introduction of the keywords