0

我有以下内容来启动分析 API:

while (!MemoryProfiler.IsActive || !MemoryProfiler.CanControlAllocations)
{
    _presenter.WriteLine("Press enter to try to attach.");
    Console.ReadKey();
    Thread.Sleep(250);
}

MemoryProfiler.EnableAllocations();

但是,如果我运行它并将 dotMemory 附加到它,那么MemoryProfiler.CanControlAllocations它总是falseMemoryProfiler.IsActive变成true)。

如果我让 dotMemory 启动应用程序,那么它会按预期工作,并且两者都评估为true.

但是,如果我将 a 替换为whileaConsole.Read()和 an,if如下所示:

Console.WriteLine("Press enter when connected.");
Console.ReadLine();

if (MemoryProfiler.IsActive && MemoryProfiler.CanControlAllocations)
{
    MemoryProfiler.EnableAllocations();
}

然后它工作正常。

这是怎么回事?循环如何while改变这样的行为?

更奇怪的行为

如果我运行以下命令(if注释掉)

Console.WriteLine("Press enter when connected.");
Console.ReadLine();

Console.WriteLine($"MemoryProfiler.IsActive: {MemoryProfiler.IsActive}");
Console.WriteLine($"MemoryProfiler.CanControlAllocations: {MemoryProfiler.CanControlAllocations}");

//if (MemoryProfiler.IsActive && MemoryProfiler.CanControlAllocations)

MemoryProfiler.EnableAllocations();

Console.WriteLine("Attached.");

然后我得到输出:

Press enter when connected.

MemoryProfiler.IsActive: True
MemoryProfiler.CanControlAllocations: False

然后在调用时引发异常EnableAllocations()

JetBrains.Profiler.Windows.Api.ProfilingApiException: 'Method isn't supported'

我希望那是因为MemoryProfiler.CanControlAllocationsis false

但是,如果我取消注释该if声明:

Console.WriteLine("Press enter when connected.");
Console.ReadLine();

Console.WriteLine($"MemoryProfiler.IsActive: {MemoryProfiler.IsActive}");
Console.WriteLine($"MemoryProfiler.CanControlAllocations: {MemoryProfiler.CanControlAllocations}");

if (MemoryProfiler.IsActive && MemoryProfiler.CanControlAllocations)

    MemoryProfiler.EnableAllocations();

Console.WriteLine("Attached.");

然后一切正常,我得到了预期的输出:

Press enter when connected.

MemoryProfiler.IsActive: True
MemoryProfiler.CanControlAllocations: False
Attached.
4

1 回答 1

1

MemoryProfiler.CanControlAllocations始终false 处于附加模式,因为无法收集分配。请参阅COR_PRF_ALLOWABLE_AFTER_ATTACH,COR_PRF_ENABLE_OBJECT_ALLOCATEDCOR_PRF_MONITOR_OBJECT_ALLOCATED标志corprof.idl

PS MemoryProfiler.EnableAllocations()并且MemoryProfiler.DisableAllocations()总是在附加模式下抛出异常。

以下代码将在启动和附加模式下工作:

while (!MemoryProfiler.IsActive)
  Thread.Sleep(500);

// do something here #1
MemoryProfiler.Dump();

// do something here #2.1
if (MemoryProfiler.CanControlAllocations)
  MemoryProfiler.EnableAllocations();
// do something here #2.2, here will be collected allocations, but only in start mode
if (MemoryProfiler.CanControlAllocations)
  MemoryProfiler.DisableAllocations();
// do something here #2.3
MemoryProfiler.Dump();

// do something here #3
MemoryProfiler.Dump();

if (MemoryProfiler.CanDetach)
  MemoryProfiler.Detach();

PPS这是 JetBrains 的官方答案 :-)

于 2017-04-12T20:48:55.870 回答