【发布时间】:2012-12-01 10:15:23
【问题描述】:
我是 C# 和线程的新手,这是一个非常简单的问题,但我真的卡住了。我确实在这个网站上搜索过,但找不到与我的场景类似的答案:
我有一个方法说 Parent() 并且我创建了一个类型化列表,每次我将它传递给一个任务。我有什么时候清除列表和释放内存的问题,因为它一直在增长。我尝试在任务结束时清除列表,如果我使用 Parent 方法清除列表,则线程中的列表为空。
有人可以帮我吗?我知道这是一个非常简单的问题,但不胜感激。
public void Parent()
{
List<MyType> list = new List<MyType>();
for (int i = 0; i< N; i++)
{
list.Add(new MyType {Var = "blah"});
if ( i% 10 == 0) //every tentth time we send a task out tou a thread
{
Task.Factory.StartNew(() => WriteToDB(new List<MyType>(list)));
//here I am sending a new instance of the list
//Task.Factory.StartNew(() => WriteToDB((list)));
//here I am sending same instance
list.Clear();
//if I clear here the list sent to the WriteToDB is empty
//if I do not, the memory keeps growing up and crashes the app
}
private void WriteToDB(List<MyType> list)
{
//do some calculations with the list
//insert into db
list.Clear();
}
}
}
【问题讨论】:
-
您能否显示完整的类定义,而且您似乎将一个方法嵌套在另一个方法中,我是类的父类..?
标签: c# multithreading c#-4.0 task-parallel-library