C#在使用异步委托完成时获得通知

本文探讨了在C#中如何使用BeginInvoke方法启动异步委托,并通过回调委托在目标线程上执行DelegateCallback方法。文章详细介绍了异步委托的处理流程,包括回调的触发条件及线程状态的影响。

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

使用BeginInvoke方法来启动异步委托,使用第一个参数向异步委托传递一个回调委托。该回调委托将在异步委托完成处理时在方法被调用的线程上调用DelegateCallback方法。如果该线程当前正在执行其他代码,回调将等待至线程空闲为止。线程将继续存在,因为系统知道一个回调在挂起,所以不需要考虑回调准备好调用时线程不存在的情况。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        public delegate int AsyncInvoke(); //定义AsyncInvoke委托
        
        public class TestAsyncInvoke
        {
            /// <summary>
            /// 定义委托调用的静态方法
            /// </summary>
            /// <returns></returns>
            public static int Method1()
            {
                Console.WriteLine($"Invoke Method1 on thread {Thread.CurrentThread.ManagedThreadId}");
                return (1);
            }
        }
        public class AsyncAction
        {
            public void CallbackAsyncDelegate()
            {
                AsyncCallback callBack = DelegateCallback;

                AsyncInvoke method1 = TestAsyncInvoke.Method1;
                Console.WriteLine($"Calling BeginInvoke on thread{Thread.CurrentThread.ManagedThreadId}");
                IAsyncResult asyncResult = method1.BeginInvoke(callBack, method1);

                return;
            }
            private static void DelegateCallback(IAsyncResult iresult)
            {
                Console.WriteLine($"Getting callback on thread{Thread.CurrentThread.ManagedThreadId}");
                AsyncResult asyncResult = (AsyncResult)iresult;
                AsyncInvoke method1 = (AsyncInvoke)asyncResult.AsyncDelegate;

                int retVal = method1.EndInvoke(asyncResult);
                Console.WriteLine($"ret (callback):{retVal}");
            }
        }
        //获得一个匿名委托的完成通知
        static void Main(string[] args)
        {
            AsyncAction t = new AsyncAction();
            t.CallbackAsyncDelegate();
            Console.ReadLine();
        }      
    }
}

 上述代码的输出如下。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值