gpt4 book ai didi

c# - `using` 完成后断开与事件的连接

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:19 25 4
gpt4 key购买 nike

我目前有这样的代码,一个 async 方法:

MyEventHandler handler = (sender, e) => ...

Foo.My += handler;

await Foo.Bar(); // Fires event `My`

Foo.My -= handler;

我想使用 using 语句来处理此代码的前后性质。也许是这样的:

using (ListenUntilDispose(Foo.My, handler))
{
await Foo.Bar();
}

但我想不出要写ListenTemporarily

有办法吗?

最佳答案

是的,有,但不幸的是,一般地执行此操作并不简单,因为事件在 C# 中没有具体化 - 我的意思是,您不能传递对事件的引用。

在 Reactive Extensions 中,这是通过使用反射来解决的,因此您可以通过传递定义事件的对象将事件传递给函数,并将事件名称作为字符串:

using(ListenUntilDispose(Foo, "My", handler))
{
await Foo.Bar();
}

但是,我的 reflection-fu 不是很强,而且你也失去了静态类型安全性,这意味着编译器无法检查 handler 是否真的与 Foo.My< 匹配。如果您的目标确实是“我想使用 using”而不一定是“我想要最容易阅读的解决方案”,那么这里还有另一个建议,虽然不太舒服但也可能适合您:

class DelegateDisposable : IDisposable
{
private readonly Action m_dispose;
public DelegateDisposable(Action onDispose)
{
m_dispose = onDispose;
}

public void Dispose()
{
m_dispose();
}
}

用法是:

Foo.My += handler;
using(new DelegateDisposable(() => Foo.My -= handler))
{
await Foo.Bar();
}

免责声明:写在编辑框中,所以未经测试:)

关于c# - `using` 完成后断开与事件的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644565/

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