How to create predicted output using Lazy <StackFrame>

I am working on some internal logging systems and for the sake of performance it seems like a good idea to get lazy StackFrame. I want to use this StackFrameto get the first method outside the scope of logging.

My initial idea was as follows:

using System;
using System.Diagnostics;
using NUnit.Framework;

[TestFixture]
public class Test
{
    [Test]
    public void Caller()
    {
        NeedsToNowCaller();
    }

    public void NeedsToNowCaller()
    {
        Processor.GetName(() => new StackFrame(4));

        Really();
        Assert.AreEqual("Caller", Processor.stackFrame.Value.GetMethod().Name);
    }

    public void Really()
    {
        Assert.AreEqual("Caller",Processor.stackFrame.Value.GetMethod().Name);
    }
}

public static class Processor
{
    public static Lazy<StackFrame> stackFrame;

    public static void GetName(Func<StackFrame> stackFrameProvider)
    {
        stackFrame = new Lazy<StackFrame>(stackFrameProvider);
    }
}

But when you change these lines:

    Really();
    Assert.AreEqual("Caller", Processor.stackFrame.Value.GetMethod().Name);

The results are unpredictable as the call stack changes. In any case, to get snapped to a local area / frame through closure, while maintaining laziness.

The only solution I can think of is to go through StackTrace until I find the first frame with an unknown method.

I really hope that there will be a better solution.

+3
1

, , . , - , , , "" ( ...)?

public void DoStuff()
{
    int index = 0;
    StackFrame frame = new StackFrame(index++);
    while (this.GetType().Name.Equals(frame.GetMethod().DeclaringType.Name))
    {
        frame = new StackFrame(index++);
    }
    //...
}
0

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


All Articles