C# AsyncCallback 委托

AsyncCallback 委托
----------------------------------------------------------------------------------------------------------------------------------------------------------------
引用在相应异步操作完成时调用的方法。
命名空间: System 
程序集: mscorlib(在 mscorlib.dll 中) 

语法
----------------------------------------------------------------------------------------------------------------------------------------------------------------

[SerializableAttribute]
[ComVisibleAttribute(true)]
public delegate void AsyncCallback(
    IAsyncResult ar
)

参数
ar 
类型: System.IAsyncResult
异步操作的结果。

备注
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Use an AsyncCallback delegate to process the results of an asynchronous operation in a separate thread. The AsyncCallback delegate represents a callback method that is called when the asynchronous operation completes. The callback method takes an IAsyncResult parameter, which is subsequently used to obtain the results of the asynchronous operation.

For more information about asynchronous programming, see 使用 AsyncCallback 委托结束异步操作 and 使用 AsyncCallback 委托和状态对象 in 基于事件的异步模式 (EAP).

示例
----------------------------------------------------------------------------------------------------------------------------------------------------------------
The following code example demonstrates using asynchronous methods in the Dns class to retrieve Domain Name System (DNS) information for user-specified computers. This example creates an AsyncCallback delegate that references the ProcessDnsInformation method. This method is called once for each asynchronous request for DNS information.
下面的代码示例演示如何在Dns类中使用异步方法检索用户指定计算机的域名系统(Dns)信息。这个例子创建了一个引用ProcessDnsInformation方法的AsyncCallback委托。对于每个请求DNS信息的异步请求,都会调用此方法一次。

/*
The following example demonstrates using asynchronous methods to get Domain Name System information for the specified host computers. 
This example uses a delegate to obtain the results of each asynchronous operation.
下面的示例演示如何使用异步方法获取指定主机的域名系统信息。
本例使用委托来获取每个异步操作的结果。
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Specialized;
using System.Collections;

namespace Examples.AdvancedProgramming.AsynchronousOperations
{
    public class UseDelegateForAsyncCallback
    {
        static int requestCounter;
        static ArrayList hostData = new ArrayList();
        static StringCollection hostNames = new StringCollection();
        static void UpdateUserInterface()
        {
            // Print a message to indicate that the application
            // is still working on the remaining requests.
            Console.WriteLine("{0} requests remaining.", requestCounter);
        }
        public static void Main()
        {
            // Create the delegate that will process the results of the 
            // asynchronous request.
            AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation);
            string host;
            do
            {
                Console.Write(" Enter the name of a host computer or <enter> to finish: ");
                host = Console.ReadLine();
                if (host.Length > 0)
                {
                    // Increment the request counter in a thread safe manner.
                    Interlocked.Increment(ref requestCounter);
                    // Start the asynchronous request for DNS information.
                    Dns.BeginGetHostEntry(host, callBack, host);
                 }
            } while (host.Length > 0);
            // The user has entered all of the host names for lookup.
            // Now wait until the threads complete.
            while (requestCounter > 0)
            {
                UpdateUserInterface();
            }
            // Display the results.
            for (int i = 0; i< hostNames.Count; i++)
            {
                object data = hostData [i];
                string message = data as string;
                // A SocketException was thrown.
                if (message != null)
                {
                    Console.WriteLine("Request for {0} returned message: {1}", 
                        hostNames[i], message);
                    continue;
                }
                // Get the results.
                IPHostEntry h = (IPHostEntry) data;
                string[] aliases = h.Aliases;
                IPAddress[] addresses = h.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases for {0}", hostNames[i]);
                    for (int j = 0; j < aliases.Length; j++)
                    {
                        Console.WriteLine("{0}", aliases[j]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses for {0}", hostNames[i]);
                    for (int k = 0; k < addresses.Length; k++)
                    {
                        Console.WriteLine("{0}",addresses[k].ToString());
                    }
                }
            }
       }

        // The following method is called when each asynchronous operation completes.
        static void ProcessDnsInformation(IAsyncResult result)
        {
            string hostName = (string) result.AsyncState;
            hostNames.Add(hostName);
            try 
            {
                // Get the results.
                IPHostEntry host = Dns.EndGetHostEntry(result);
                hostData.Add(host);
            }
            // Store the exception message.
            catch (SocketException e)
            {
                hostData.Add(e.Message);
            }
            finally 
            {
                // Decrement the request counter in a thread-safe manner.
                Interlocked.Decrement(ref requestCounter);
            }
        }
    }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
异步回调函数(asynchronous callback)是一种常见的编程模式,用于处理异步任务的结果。在异步编程中,当一个任务完成后,会调用一个回调函数来处理结果。这个回调函数通常作为参数传递给异步任务,以便在任务完成后被调用。 异步回调函数的使用可以有效地避免阻塞主线程,提高程序的性能和响应性。当一个异步任务完成时,它会将结果放入任务队列中,然后主线程会从任务队列中取出结果,并调用相应的回调函数来处理结果。这样可以确保在任务完成之前,主线程可以继续执行其他任务,而不需要等待异步任务的完成。 闭包(closure)在异步编程中也经常被使用。闭包是指一个函数能够访问其定义时的词法环境中的变量。在JavaScript中,闭包可以用来保存异步回调函数所需的上下文信息,以便在回调函数被调用时能够正确地访问这些信息。 总结来说,异步回调函数是一种处理异步任务结果的方式,它通过将回调函数作为参数传递给异步任务来实现。闭包在异步编程中常用于保存上下文信息,以便在回调函数中能够正确地访问这些信息。 #### 引用[.reference_title] - *1* *2* [AsyncCallback 异步回调委托](https://blog.csdn.net/weixin_34268610/article/details/94654999)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v4^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__Benco

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值