gpt4 book ai didi

c# - 为什么要在异步匿名函数中包装事件分配?

转载 作者:行者123 更新时间:2023-11-30 12:20:07 26 4
gpt4 key购买 nike

在匿名异步函数中包装事件分配有什么意义吗?

假设这段代码在某个适配器类中:

public event Action<int> someAction;

下面的代码在其他一些设置 Action 的类中:

示例 1:

_someAdapter.someAction += async (someParameter) =>
{
await HandleAction(someParamter);
};

在这种情况下,HandleAction 具有异步任务返回类型。

示例 2:

_someAdapter.someAction += HandleAction;

在这种情况下,HandleAction 具有 async void 返回类型。

同样的问题适用于按钮单击事件处理程序等。我已经看到了这两个示例,并且想知道为什么有时会包装它。从我的测试来看,似乎没有任何区别。

最佳答案

我相信使用匿名处理程序包装器,您将能够让 C# 垃圾收集器在 this(在示例 1 中)即将被删除时“脱钩”并销毁处理程序销毁。

this 之外的事件处理程序(在您的示例中不是这种情况)会受到特别注意,包装它看起来是个不错的选择。

如果 this 会存在很长时间,并且您有可能必须再次 Hook 该事件 you should use another strategy to avoid memory leak喜欢讨论的on this question

返回类型差异are related to exception handlingit's ok to use an async void on top-level methods and async event handlers .

希望对你有帮助。

关于c# - 为什么要在异步匿名函数中包装事件分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com