[英]Why is my code causing unmanaged memory to slowly increase causing gen0 collections?
在單元測試中運行以下代碼時,我發現性能監視器中的專用字節和工作集緩慢增加,而dotMemory中的非托管內存則緩慢增加。 我已經在dotPeek中反編譯了源代碼,似乎找不到任何異常。 有任何想法嗎? 這是代碼:
[TestMethod]
public void TestEnumeratorMoveNext()
{
//Dictionary<string, int>[] outDict = new Dictionary<string, int>[32].Select(x => x = new int[100].ToDictionary(y => Guid.NewGuid().ToString())).ToArray();
var outDict = new Dictionary<string, int>[32];
for (int j = 0; j < 32; j++)
{
outDict[j] = new Dictionary<string, int>();
for(int q = 0; q < 100; q++)
{
outDict[j].Add(Guid.NewGuid().ToString(), 0);
}
}
for (int i = 0; i < 10000; i++)
{
var enumerator = new Enumerator<string, int>(outDict);
while (enumerator.MoveNext()) { }
Thread.Sleep(1000 / 60);
}
}
public struct Enumerator<TKey, TValue> : IEnumerator<KeyValuePair<TKey, TValue>>
{
private Dictionary<TKey, TValue>[] dictionary;
private int partition;
private IEnumerator<KeyValuePair<TKey, TValue>> enumerator;
private bool moveNext;
private int totalPartitions;
internal Enumerator(Dictionary<TKey, TValue>[] dictionary)
{
this.dictionary = dictionary;
this.totalPartitions = dictionary.Count();
partition = 0;
enumerator = new Dictionary<TKey, TValue>.Enumerator();
moveNext = false;
}
public bool MoveNext()
{
if (partition < totalPartitions)
{
do
{
var outDict = dictionary[partition];
if (!moveNext)
enumerator = outDict.GetEnumerator();
moveNext = enumerator.MoveNext();
if (!moveNext)
{
enumerator.Dispose();
partition++;
}
} while (!moveNext && partition < totalPartitions);
return true;
}
partition = totalPartitions + 1;
enumerator = new Dictionary<TKey, TValue>.Enumerator();
moveNext = false;
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return enumerator.Current;
}
}
public void Dispose()
{
enumerator.Dispose();
}
object IEnumerator.Current
{
get
{
return new KeyValuePair<TKey, TValue>(Current.Key, Current.Value);
}
}
public void Reset()
{
throw new NotSupportedException();
}
}
我感謝任何人都能給我的幫助。 提前致謝。
解決方案是將Enumerator結構中的private IEnumerator<KeyValuePair<TKey, TValue>> enumerator
更改為private Dictionary<TKey, TValue>.Enumerator enumerator
。 不再有G0 GC。 如果有人知道為什么會這樣,我很想聽聽解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.