2

I'd like to define a compilation symbol like PROFILE only when I'm profiling a C# project in Visual Studio. In a normal debug or release build it should not be defined.

So the code between #if and #endif gets only compiled when profiling.

#if PROFILE
  DataCollection.StartProfile(ProfileLevel.Process, DataCollection.CurrentId); 
#endif

It should be a compile time check, no runtime check. The reason is that some of our team have no profiler on their PCs (not included in VS 2012 Standard) and we would like the code to compile on any system without changes.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Knasterbax
  • 7,895
  • 1
  • 29
  • 23

1 Answers1

3

Create a new configuration:

  • Click Build then select Configuration Manager.
  • Click Active solution configuration and select New.
  • Type Profile in Name and select which configuration will be used as template (for profiling I guess Release).
  • Confirm with OK, it'll create new configurations named Profile for each project in your solution.
  • Open properties of each project, and in the Build tab add PROFILE symbol in Conditional compilation symbols then save properties.

Now when you build the Profile configuration the PROFILE symbol will be defined. I suggest you take a look to this post too, if you automate your builds you may keep your PROFILE symbol out of the solution using MSBuild properties via command-line (I suppose you do not build for profiling very often).

EDIT With configuration you can do that but it won't save you from a broken reference to Microsoft.VisualStudio.Profiler.dll). What I suggest is to move all this code to another library that you'll ship to them compiled. There you'll expose just a method:

public static class ProfilingHelpers
{
    [Conditional("PROFILE")]
    public static void StartProfiling()
    {
        DataCollection.StartProfile(ProfileLevel.Process, DataCollection.CurrentId);
    }
}

In your code you'll always call it but it'll be executed only when PROFILE is defined (so you won't need to add a new configuration to each project but to one DLL only).

jpaugh
  • 6,634
  • 4
  • 38
  • 90
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208