user65199
user65199

Reputation:

StackTrace from Exception on different thread?

There is a constructor on StackTrace that takes an exeption as an argument. All fine and well, but I noticed that all the other constructors say that it will get the StackTrace from the current thread, but the constructor taking the exception does not say anything about that other than

The resulting stack trace describes the stack at the time of the exception.

I just want to be sure that I will get the correct StackTrace of an exception even if I create the StackTrace on a different thread that the exception was created in when I create the StackTrace from an exception in another thread.

Can someone please confirm?

Upvotes: 1

Views: 715

Answers (2)

Mattias S
Mattias S

Reputation: 4808

Seems easy enough to try, unless I'm missing something. This prints the right stack trace for me.

static Exception threadEx;

static void Main()
{
    Thread worker = new Thread(DoWork);
    worker.Start();
    worker.Join();

    if (threadEx != null) {
        StackTrace trace = new StackTrace(threadEx);
        Console.WriteLine(trace);
    }
}

static void DoWork()
{
    try {
        throw new Exception("Boom!");
    }
    catch (Exception ex) {
        threadEx = ex;
    }
}

Upvotes: 1

codekaizen
codekaizen

Reputation: 27419

It will create the StackTrace for the thread it's called on (internally, it calls 'CaptureStackTrace' with for the parameter 'targetThread', which indicates the current thread is requested). The only ctor which creates for another thread is the one which takes a Thread instance.

Upvotes: 1

Related Questions