使用 AsyncCallback 处理异步调用

本文介绍了一个使用 C# 进行异步调用的简单示例,展示了如何利用委托和回调函数实现主线程不受阻塞的加法运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文章 原文

        异步调用可以避免主线程受工作线程阻塞,即工作线程执行的过程中,主线程依然可以往下运行,不必等待工作线程完成。下面是一个简单的异步调用加法函数的例子。

using System;
using System.Threading;
// the namespace for AsyncResult.
using System.Runtime.Remoting.Messaging;

namespace AsyncCallback
{
    // Delegate for add method.
    public delegate int TwoOperands(int a,int b);

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main is running on thread " + Thread.CurrentThread.ManagedThreadId);
            TwoOperands operation = new TwoOperands(Add);
            //async calling the add.
            //new System.AsyncCallback(CallbackHandler) 回调处理函数, 异步调用结束后,runtime会调用该函数。
            // "Async parameter" 作为回调参数,传给回调函数,通过 AsyncResult.AsyncState 获取
            operation.BeginInvoke(2, 3, new System.AsyncCallback(CallbackHandler), "Async parameter");
            Console.WriteLine("Main is running on thread " + Thread.CurrentThread.ManagedThreadId);
            Console.Read();
        }

        /// <summary>
        /// 回调处理函数
        /// </summary>
        /// <param name="iar">回调参数</param>
        static void CallbackHandler(IAsyncResult iar)
        {
            Console.WriteLine("CallbackHandler is running on thread " + Thread.CurrentThread.ManagedThreadId);           
            AsyncResult ar = (AsyncResult)iar;
            // 获取原委托对象。
            TwoOperands operation = (TwoOperands)ar.AsyncDelegate;
            // 结束委托调用。
            int i = operation.EndInvoke(iar);
            // 打印异步调用传入的参数。
            Console.WriteLine("The Async calling parameter is " + ar.AsyncState);
            Console.WriteLine("The adding result is " + i);           
        }

        static int Add(int i, int j)
        {
            Console.WriteLine("Add is running on thread " + Thread.CurrentThread.ManagedThreadId + "...");
            Thread.Sleep(5000);
            return i + j;
        }
    }
}

输出结果

image

由此可见,异步调用的函数,与异步回调函数是在同一线程上运行的。

转载于:https://www.cnblogs.com/philzhou/archive/2011/02/23/1962280.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值