我正在处理一个小型的.NET Standard 2.0 logging library,而且我无法找到一种方法来可靠地获取当前进程在所有平台上使用的内存,尤其是在UWP上
现在我正在使用此代码(.NET Standard 2.0):
long memory = Process.GetCurrentProcess().PrivateMemorySize64;
哪个正常,但会在UWP上抛出一个不错的PlatformNotSupportedException
异常(实际上,这只是在DEBUG模式下,而在RELEASE中直接抛出一个TypeLoadException
由于某种原因加上一堆其他P / Invoke异常。)
这里的问题是UWP显然不支持该API,我应该使用:
long memory = (long)MemoryManager.AppMemoryUsage;
问题是MemoryManager是一个仅支持UWP的API,它在.NET Standard 2.0中不存在。现在,我想到的第一个解决方法是在库中公开一个设置,让用户手动设置一个自定义Func<long>
委托来检索当前的内存使用情况,这样如果它知道默认方法就赢了。在当前平台上工作,可以覆盖它。
这看起来似乎是一个糟糕的伎俩,而且我希望将所有内容都保留在库中。所以我的问题是:
有没有办法可以在任何支持.NET Standard 2.0库的平台上可靠地检索当前的流程/应用程序使用情况?
谢谢!
答案 0 :(得分:1)
Maybe a little dirty, but the following could work (may add some better error handling and such):
public static long GetProcessMemory()
{
try
{
return Process.GetCurrentProcess().PrivateMemorySize64;
}
catch
{
var type = Type.GetType("Windows.System.MemoryManager, Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime");
return Convert.ToInt64(type.GetProperty("AppMemoryUsage", BindingFlags.Public | BindingFlags.Static).GetValue(null, null));
}
}
I use reflection to get around the fact that MemoryManager
is not available for .NET Standard at compile time, but for the UWP runtime. This way the same assembly would work for both runtimes.
But in general I would prefer a way which generates a fitting assembly per runtime like suggested by Martin.
答案 1 :(得分:0)
I think you could use the same trick previously used for Portable Class Libraries - Bait and Switch. It is still compatible with .NET Standard 2.0. This way you can create a specific implementation for UWP and fall back to the standard implementation otherwise.