How to wrap a thread of an unsafe class into one that is thread safe without packing each member function

I want the ability to take a class (written and maintained by a third party), wrap it with some kind of magical C # sugar, which allows me to wrap each member function (or more) using a special locking mechanism (or a registration mechanism or whatever).

For instance,

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(); 

Output

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

Now I think I can do this with DynamicObjects and TryInvokeMember , but then I lose all the type checks and tab completion that I like in C #. In this example, I mentioned lock for thread safety, but I'm looking for a general way to do this. This code is intended for testing equipment in real time, which requires additional levels of repetition, logging, etc.

+4
source share
2 answers

I found the answer already on SO.

How to transfer each function to the project?

Powerful AOP (programming aspect oriented).

It is not built into Visual Studio. There PostSharp and AspectDNG:

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

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

+2
source

You can learn Aspect Oriented Programming .

PostSharp is a very popular structure that can enter code before / after calling a method, for example, stream code , here is an example on Locking .
It can also help with logging , here is an example.

+2
source

Source: https://habr.com/ru/post/1435383/


All Articles