我已将我原来的问题简化为这个测试。
使用这个类:
public class Unmanaged : IDisposable
{
private IntPtr unmanagedResource;
public Unmanaged()
{
this.unmanagedResource = Marshal.AllocHGlobal(10 * 1024 * 1024);
}
public void DoSomethingWithThisClass()
{
Console.WriteLine($"{DateTime.Now} - {this.unmanagedResource.ToInt64()}");
}
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
Marshal.FreeHGlobal(unmanagedResource);
disposedValue = true;
}
}
~Unmanaged() {
Dispose(false);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
我有这两个测试:
public class UnitTest1
{
const int Runs = 100000;
[TestMethod]
public void UsingFor()
{
for (var i = 0; i <= Runs; i++)
{
using (var unman = new Unmanaged())
{
unman.DoSomethingWithThisClass();
}
}
}
[TestMethod]
public void UsingParallelFor()
{
Parallel.For(0, Runs, new ParallelOptions() { MaxDegreeOfParallelism = 10},
index => {
using (var unman = new Unmanaged())
{
unman.DoSomethingWithThisClass();
}
});
}
}
ParallelFor 通常需要大约两倍于常规 for 的时间。根据分析器,62%-65% 的执行时间花在了 ParallelFor 的 FreeHGlobal 中。只有 52%-53% 用于 FreeHGlobal 中用于常规用途。
我认为对于现代 RAM 系统,这不会有太大的不同。有没有办法在多个进程中处理大块非托管内存?有没有办法可以将其更改为多线程?
如果我不处理每个进程中使用的 RAM(坏主意,但只是为了测试),Parallel For 的速度是原来的两倍,但是我只能打开其中大约 4-5 个(它们是大量的图像数据)在应用程序崩溃之前的同一时间(正如您所猜测的那样,内存不足异常)。
为什么对单独的对象进行多个 Dispose 操作会减慢速度?
如果这是唯一的选择,我可以让它们保持单线程,但我希望加快速度。
谢谢你。