开发者

c# Task class and memory leak

I have an application which handles data from text file - it reads a line from the file then handles it and then puts a result in another file. After handling one row it handles the next one until the whole file is done. Some rows from the file is very time-consuming for handling. So I decided to put handling-logic in separate thread and if handling takes longer then 10 sec. I kill the thread. So my code is like this:

public class Handler
{
   public void Handle(string row)
   {
      // Perform handling
   }
}

public class Program
{
   private static bool HandleRow(string row)
   {
      Task task = new Task(() => new Handler().Handle(row));
      task.Start(); // updated
      var waitResult = task.Wait(timeout); // timeout is 10 sec.
      if(waitResult == false || task.IsFaulted)
         return false;
      return true;
   }

   public static void Main()
   {
      foreach(var row in GetRowsToHandle())
         HandleRow(row);
   }
}

but somehow when running the program I get out of memory exception. It seems that memory is not released properly.

Does anyone know why memory leaks might happen?

UPDATED

I forgot to include task.Start() in m开发者_如何学Goy code sniffer. Now I put it there


Task is Disposable : task.Dispose();


Your 10s timeout only times out the task. It doesn't stop Handle() from executing (if indeed it ever starts - I can't see a Start there). It just means you locally see a timeout on task.

Also, it depends in part on what GetRowsToHandle() does - does it return a non-buffered sequence, or is it a list, etc.

While Task does support cancellation, this requires co-operation from the implementation. To be honest, since you aren't doing anything async you might be better off just handling your own "have I taken too long" basic timeout in Handle(). A thread-abort (the other option) is not to be recommended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜