使用 AsyncCallback 委托结束异步操作

 

在等待异步操作结果的同时可以进行其他工作的应用程序不应在操作完成之前阻止等待。可以使用下列方法之一来在等待异步操作完成的同时继续执行指令。

  • 可使用 AsyncCallback 委托来处理另一个线程中的异步操作的结果。本主题中演示了此方法。
  • 可使用异步操作的 BeginOperationName 方法返回的 IAsyncResult IsCompleted 属性来确定此操作是否已完成。有关演示此方法的示例,请参见轮询异步操作的状态

示例

下面的代码示例演示如何使用 Dns 类中的异步方法来检索用户指定的计算机的域名系统 (DNS) 信息。此示例创建了引用 ProcessDnsInformation 方法的 AsyncCallback 委托。对各个针对 DNS 信息发出的异步请求,将分别调用一次此方法。

请注意,用户指定的主机被传递给了 BeginGetHostByNameObject 参数。有关演示如何定义和使用更复杂的状态对象的示例,请参见使用 AsyncCallback 委托和状态对象

  1. /*
  2. The following example demonstrates using asynchronous methods to
  3. get Domain Name System information for the specified host computers.
  4. This example uses a delegate to obtain the results of each asynchronous 
  5. operation.
  6. */
  7. using System;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. using System.Collections.Specialized;
  12. using System.Collections;
  13. namespace Examples.AdvancedProgramming.AsynchronousOperations
  14. {
  15.     public class UseDelegateForAsyncCallback
  16.     {
  17.         static int requestCounter;
  18.         static ArrayList hostData = new ArrayList();
  19.         static StringCollection hostNames = new StringCollection();
  20.         static void UpdateUserInterface()
  21.         {
  22.             // Print a message to indicate that the application
  23.             // is still working on the remaining requests.
  24.             Console.WriteLine("{0} requests remaining.", requestCounter);
  25.         }
  26.         public static void Main()
  27.         {
  28.             // Create the delegate that will process the results of the 
  29.             // asynchronous request.
  30.             AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation);
  31.             string host;
  32.             do
  33.             {
  34.                 Console.Write(" Enter the name of a host computer or <enter> to finish: ");
  35.                 host = Console.ReadLine();
  36.                 if (host.Length > 0)
  37.                 {
  38.                     // Increment the request counter in a thread safe manner.
  39.                     Interlocked.Increment(ref requestCounter);
  40.                     // Start the asynchronous request for DNS information.
  41.                     Dns.BeginGetHostEntry(host, callBack, host);
  42.                  }
  43.             } while (host.Length > 0);
  44.             // The user has entered all of the host names for lookup.
  45.             // Now wait until the threads complete.
  46.             while (requestCounter > 0)
  47.             {
  48.                 UpdateUserInterface();
  49.             }
  50.             // Display the results.
  51.             for (int i = 0; i< hostNames.Count; i++)
  52.             {
  53.                 object data = hostData [i];
  54.                 string message = data as string;
  55.                 // A SocketException was thrown.
  56.                 if (message != null)
  57.                 {
  58.                     Console.WriteLine("Request for {0} returned message: {1}"
  59.                         hostNames[i], message);
  60.                     continue;
  61.                 }
  62.                 // Get the results.
  63.                 IPHostEntry h = (IPHostEntry) data;
  64.                 string[] aliases = h.Aliases;
  65.                 IPAddress[] addresses = h.AddressList;
  66.                 if (aliases.Length > 0)
  67.                 {
  68.                     Console.WriteLine("Aliases for {0}", hostNames[i]);
  69.                     for (int j = 0; j < aliases.Length; j++)
  70.                     {
  71.                         Console.WriteLine("{0}", aliases[j]);
  72.                     }
  73.                 }
  74.                 if (addresses.Length > 0)
  75.                 {
  76.                     Console.WriteLine("Addresses for {0}", hostNames[i]);
  77.                     for (int k = 0; k < addresses.Length; k++)
  78.                     {
  79.                         Console.WriteLine("{0}",addresses[k].ToString());
  80.                     }
  81.                 }
  82.             }
  83.        }
  84.         // The following method is called when each asynchronous operation completes.
  85.         static void ProcessDnsInformation(IAsyncResult result)
  86.         {
  87.             string hostName = (string) result.AsyncState;
  88.             hostNames.Add(hostName);
  89.             try 
  90.             {
  91.                 // Get the results.
  92.                 IPHostEntry host = Dns.EndGetHostEntry(result);
  93.                 hostData.Add(host);
  94.             }
  95.             // Store the exception message.
  96.             catch (SocketException e)
  97.             {
  98.                 hostData.Add(e.Message);
  99.             }
  100.             finally 
  101.             {
  102.                 // Decrement the request counter in a thread-safe manner.
  103.                 Interlocked.Decrement(ref requestCounter);
  104.             }
  105.         }
  106.     }
  107. }

Inserted from <http://msdn.microsoft.com/zh-cn/library/ms228972(VS.80).aspx>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值