0

I'm writing a class, that must be added as dll file to any .NET project. I'm stuck in point, where I need to make event to System.Diagnostics.StackTrace "last_method_name_changed".

So I need to find a way to detect changes in StackTrace, or create event that is raised when thread enters or exits a method. Something like:

Public Class DllClass
    Public Shared CallerTrace as StackTrace = Nothing
    Public Shared New(ByRef NewTrace as StackTrace) 'This is called from form.
        '''I know this will make a copy, but I have failed to find a solution.
        CallerTrace = NewTrace
    End Sub
    Public Shared Sub StackTrace_Changed() Handles CallerTrace.Changed
        MsgBox(CallerTrace.GetFrame(0).GetMethod.Name)
    End Sub
End Class

From the main form this should be called only once:

Dim DllCls as New DllClass(New Diagnostics.StackTrace)

I'll be grateful for any help in making "reference link" or pointer to StackTrace and event that will raise when CallerTrace.GetFrame(0).GetMethod.Name is changed.

tckmn
  • 57,719
  • 27
  • 114
  • 156

1 Answers1

1

No copy is made as StackTrace is a reference type (assigning to a reference doesn’t copy the underlying object). The ByRef in the parameter declaration is unrelated and redundant.

On the other hand you didn’t declare CallerTrace as WithEvents so you don’t actually listen to any events that are raised by it. That won’t work though, since System.Diagnostics.StackTrace declares no public events that can be listened to. Your approach for intercepting method calls fundamentally doesn’t work.

To intercept method calls in the fashion that you envisage you need to drill way further. Luckily there are libraries which already allow that, such as the AOP library PostSharp.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • I see your point, but I have another question. For example, if I create background thread, and put infinite loop to check StackTrace for changes. How can I get methods that are currently used in the main thread? –  Jan 16 '13 at 15:20
  • I don’t know whether you can get a stack trace for a separate thread at all. In fact, other answers here on Stack Overflow indicate that [this is not possible](http://stackoverflow.com/a/5307360/1968). – Konrad Rudolph Jan 16 '13 at 15:25