Search code examples
c#taskstate-machineinternal

Getting the actual this reference to the task state machine


I'm playing with the idea of tampering with the state of a tasks internal state machine, but i'm having trouble finding a way to actually access the state machine reference within my task method.

class Test
{
    async Task IndexAsync()
    {
        var nottheactualtype = GetType(); //This references the "Test" class, but this operation is actually located in the nested state machine class named "IndexAsync", in the method "MoveNext()".
        var actualcalledmethod = new StackTrace().GetFrame(0).GetMethod(); //This shows the actual method currently being run: IndexAsync.MoveNext().
        //But how do I get the reference to my current IndexAsync class?
    }
}

How can I get access to the reference of the generated state machine currently being run?


Solution

  • You can take first method call from your class on stack as variant:

    var nottheactualtype = GetType();
    var actualcalledmethod = new StackTrace().GetFrames().FirstOrDefault(x => x.GetMethod().ReflectedType == nottheactualtype);