vidstige
vidstige

Reputation: 13085

Triggering finalizer in the VS2010 debugger

Using the VS2010 debugger for managed code is it possible to trigger the finalizer thread to run?

Use Case:

Using Tasks may throw exceptions on the finalizer of the Task object if the task it self has thrown exceptions and those has not been taken care of.

Verifying a bugfix whos cause was an unhandled can be time consuming since you'll need to wait for the finalizer thread to kick in before beeing sure the fix works properly.

I usually do not code using finalizers myself since it causes lots of headache and I have also mailed Microsoft about this. But while it is like this: How can I trigger the finalizer code to run from the debugger as opposed from code.

Upvotes: 1

Views: 118

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

AFAIK there is no special way to do this from the debugger.

You can trigger it in your code:

    int i = 0, j = 1;
    new Task(() => Console.WriteLine(j/i)).Start();
    Thread.Sleep(1000); // make sure it has had plenty of time
    //GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
    //GC.WaitForPendingFinalizers();
    Console.WriteLine("Did I explode yet?");
    Console.ReadKey();

Now uncomment the two lines to see the exception appear.

Note this should only be used for scenarios like tests; you should't really use GC in your regular code.

Upvotes: 2

Related Questions