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 my code sniffer. Now I put it there
Your 10s timeout only times out the task. It doesn’t stop
Handle()from executing (if indeed it ever starts – I can’t see aStartthere). It just means you locally see a timeout ontask.Also, it depends in part on what
GetRowsToHandle()does – does it return a non-buffered sequence, or is it a list, etc.While
Taskdoes 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 inHandle(). A thread-abort (the other option) is not to be recommended.