gpt4 book ai didi

c# - 如何在不包装每个成员函数的情况下将线程不安全的类包装成线程安全的类

转载 作者:太空狗 更新时间:2023-10-30 01:22:55 31 4
gpt4 key购买 nike

我想要一个类(由第三方编写和维护),用一些神奇的 C# 糖包装它,这让我可以用自定义锁定机制(或日志记录机制或随便)。

例如,

 class Foo { // someone else wrote this and I can't touch it.
void A() {}
void B() {}
// plus 10,000 other functions I don't want to know about
}

class WrappedFoo : Foo { // this is my class, I can do what ever I want
// this is pseudo code !!
OnMemberInvoke(stuff) {
lock {
Console.WriteLine("I'm calling " + stuff);
MemberInvoke(stuff);
Console.Writeline("I'm done calling " + stuff);
}
}
// I could also deal with OnMemberInvokeStart() and OnMemberInvokeDone()
// pairwise hooks too.
}

WrappedFoo wfoo = new WrappedFoo();
wfoo.A();
wfoo.B();

输出

 I'm calling A
I'm done calling A
I'm calling B
I'm done calling B

现在我认为我可以使用 DynamicObjectsTryInvokeMember 来做到这一点,但是我失去了我喜欢 C# 的所有类型检查和制表符完成。在此示例中,我提到了用于线程安全的 lock,但我正在寻找执行此操作的通用方法。此代码旨在用于真实世界的硬件测试,需要额外的重试层、日志记录等。

最佳答案

我已经在 SO 上找到了答案。

How to wrap each function in project?

流行语是 AOP(面向方面​​的编程)。

它没有内置到 Visual Studio 中。有 PostSharp 和 AspectDNG:

http://www.sharpcrafters.com/postsharp/features

http://aspectdng.tigris.org/nonav/doc/index.html

关于c# - 如何在不包装每个成员函数的情况下将线程不安全的类包装成线程安全的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521009/

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