我有以下内容来启动分析 API:
while (!MemoryProfiler.IsActive || !MemoryProfiler.CanControlAllocations)
{
_presenter.WriteLine("Press enter to try to attach.");
Console.ReadKey();
Thread.Sleep(250);
}
MemoryProfiler.EnableAllocations();
但是,如果我运行它并将 dotMemory 附加到它,那么MemoryProfiler.CanControlAllocations
它总是false
(MemoryProfiler.IsActive
变成true
)。
如果我让 dotMemory 启动应用程序,那么它会按预期工作,并且两者都评估为true
.
但是,如果我将 a 替换为while
aConsole.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.CanControlAllocations
is 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.