将列表传递给任务

San*_*ino 5 c# multithreading task-parallel-library c#-4.0

我是C#和线程的新手,这是一个非常简单的问题,但让我真的陷入困境.我在这个网站上搜索过但找不到类似于我的场景的答案:

我有一个方法说Parent(),并且我创建了一个类型列表,每次第n次我将它传递给一个Task.我有什么时候清除列表并释放内存的问题,因为它不断增长.我在任务结束时尝试清除列表,如果我使用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(); 
      }
     }
   }
Run Code Online (Sandbox Code Playgroud)

Nic*_*ler 7

你有一个关闭错误.

lambda () => WriteToDB(new List<MyType>(list))在新的Task启动之前不会执行.这有时会在你打电话之后list.Clear().

修复是捕获lambda之外的列表副本:

var chunk = new List<MyType>(list);
Task.Factory.StartNew(() => WriteToDB(chunk));

list.Clear();
Run Code Online (Sandbox Code Playgroud)