Freigeben über


How to make your function parameter to jump over stack

I faced a interesting problem while coding today. I had call stack like the following

    FunctionD

        FunctionC

            FunctionB

                FunctionA

All of these functions have only one parameter – a stream. The functions FunctionA and FunctionD were developed by me on which I have total control where as FunctionB and FunctionD were from a assembly from a third party on which I have no control. I cannot modify body or signatures of FunctionB or FunctionC since I do not have source code and did not want to try any other hacks like refection and codeDOM. Also the FunctionD is static function as mandated by thirdparty.

FunctionD responsibility is to read a string from a stream from a specific position. FunctionD returns null or a string value. I got a new requirement that said, on one specific condition, the FunctionD should return String.Empty in place of null. The application has been designed in such a way that FunctionD cannot decide on its own due to layering and abstraction. I had to tell FunctionD to return string.empty inplace of null with the help of one bool flag. I cannot overload all of these function as I had no control over FunctionC and FunctionB. How to pass in the bool Flag to functionD? This was the problem.

    Thread.Setdata and Thread.GetData [https://msdn2.microsoft.com/en-us/library/system.threading.thread.setdata.aspx] came to my rescue. I set that bool flag from FunctionA. The running thread carried the flag all the way to functionD. In functionD , I received the flag and performed necessary action based on the flag. But beware – Thread.Setdata and ThreadGetdata may lead to scalability issues [https://blogs.msdn.com/junfeng/archive/2005/12/31/508423.aspx]. If you have scalability concern, think of using ThreadStatic variables.