System.ArgumentException:“该委托必须有一个目标(且仅有一个目标)。”

文章讲述了在.NET中,当事件或委托可能绑定多个方法时,使用BeginInvoke会引发错误,因为BeginInvoke不适用于这种情况。作者强调了应使用Invoke替代以确保正确执行。

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

正常情况

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeginInvokeTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Printed += T_Printed;
            t.Call("fjds");
            Console.ReadLine();
        }

        private static void T_Printed(string obj)
        {
            Console.WriteLine("T_Printed:" + obj);
        }
    }
    public class Test
    {
        public event Action<string> Printed;
        public void Call(string s)
        {
            this.Printed?.BeginInvoke(s, null, null);
        }
    }
}

此时正常输出fjds

出错情况

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeginInvokeTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Printed += T_Printed;
            t.Printed += T_Printed2;
            t.Call("fjds");
            Console.ReadLine();
        }

        private static void T_Printed2(string obj)
        {
            Console.WriteLine("T_Printed2:" + obj);
        }

        private static void T_Printed(string obj)
        {
            Console.WriteLine("T_Printed:" + obj);
        }
    }
    public class Test
    {
        public event Action<string> Printed;
        public void Call(string s)
        {
            this.Printed?.BeginInvoke(s, null, null);
        }
    }
}

这个仅仅比上面多绑定了一个方法就报错了。
在这里插入图片描述

将上述的Printed由事件改成委托,一样报错

结论

使用事件或者委托BeginInvoke需要注意:如果事件或者委托可能绑定多个方法,不能用BeginInvoke,需要使用Invoke

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值