Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Приложения, которые не могут продолжать выполнять другие действия, ожидая результатов асинхронной операции, должны блокироваться до завершения операции. Используйте один из следующих параметров, чтобы заблокировать основной поток приложения во время ожидания выполнения асинхронной операции:
Используйте свойство AsyncWaitHandle объекта IAsyncResult, возвращаемого методом асинхронной операции BeginOperationName. Этот подход демонстрируется в этом разделе.
Вызовите метод EndOperationName асинхронной операции. Пример, демонстрирующий этот подход, см. в разделе "Блокировка выполнения приложения путем завершения асинхронной операции".
Приложения, использующие один или несколько WaitHandle объектов для блокировки до завершения асинхронной операции, обычно вызывают метод BeginOperationName , выполняют любую работу, которая может выполняться без результатов операции, а затем блокируется до завершения асинхронных операций. Приложение может блокировать одну операцию, вызвав один из WaitOne методов с помощью .AsyncWaitHandle Чтобы заблокировать выполнение, ожидая завершения набора асинхронных операций, сохраните связанные AsyncWaitHandle объекты в массиве и вызовите один из WaitAll методов. Чтобы заблокировать выполнение во время ожидания завершения любой из асинхронных операций из набора, сохраните связанные AsyncWaitHandle объекты в массиве и вызовите один из WaitAny методов.
Пример
В следующем примере кода показано использование асинхронных методов в классе DNS для получения сведений о системе доменных имен для указанного пользователем компьютера. В примере демонстрируется блокировка с использованием WaitHandle, связанная с асинхронной операцией. Обратите внимание, что null
(Nothing
в Visual Basic) передается для BeginGetHostByNamerequestCallback
параметров и stateObject
параметров, так как они не требуются при использовании этого подхода.
/*
The following example demonstrates using asynchronous methods to
get Domain Name System information for the specified host computer.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class WaitUntilOperationCompletes
{
public static void Main(string[] args)
{
// Make sure the caller supplied a host name.
if (args.Length == 0 || args[0].Length == 0)
{
// Print a message and exit.
Console.WriteLine("You must specify the name of a host computer.");
return;
}
// Start the asynchronous request for DNS information.
IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);
Console.WriteLine("Processing request for information...");
// Wait until the operation completes.
result.AsyncWaitHandle.WaitOne();
// The operation completed. Process the results.
try
{
// Get the results.
IPHostEntry host = Dns.EndGetHostEntry(result);
string[] aliases = host.Aliases;
IPAddress[] addresses = host.AddressList;
if (aliases.Length > 0)
{
Console.WriteLine("Aliases");
for (int i = 0; i < aliases.Length; i++)
{
Console.WriteLine($"{aliases[i]}");
}
}
if (addresses.Length > 0)
{
Console.WriteLine("Addresses");
for (int i = 0; i < addresses.Length; i++)
{
Console.WriteLine($"{addresses[i].ToString()}");
}
}
}
catch (SocketException e)
{
Console.WriteLine($"Exception occurred while processing the request: {e.Message}");
}
}
}
}
' The following example demonstrates using asynchronous methods to
' get Domain Name System information for the specified host computer.
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
namespace Examples.AdvancedProgramming.AsynchronousOperations
Public Class WaitUntilOperationCompletes
Public Shared Sub Main(args() as String)
' Make sure the caller supplied a host name.
If (args.Length = 0)
' Print a message and exit.
Console.WriteLine("You must specify the name of a host computer.")
End
End If
' Start the asynchronous request for DNS information.
Dim result as IAsyncResult = Dns.BeginGetHostEntry(args(0), Nothing, Nothing)
Console.WriteLine("Processing request for information...")
' Wait until the operation completes.
result.AsyncWaitHandle.WaitOne()
' The operation completed. Process the results.
Try
' Get the results.
Dim host as IPHostEntry = Dns.EndGetHostEntry(result)
Dim aliases() as String = host.Aliases
Dim addresses() as IPAddress = host.AddressList
Dim i as Integer
If aliases.Length > 0
Console.WriteLine("Aliases")
For i = 0 To aliases.Length - 1
Console.WriteLine("{0}", aliases(i))
Next i
End If
If addresses.Length > 0
Console.WriteLine("Addresses")
For i = 0 To addresses.Length - 1
Console.WriteLine("{0}", addresses(i).ToString())
Next i
End If
Catch e as SocketException
Console.WriteLine("An exception occurred while processing the request: {0}" _
, e.Message)
End Try
End Sub
End Class
End Namespace