I want to know what the best way to process the results of a long-running process serially but on a low-priority thread using the .NET 4.0 Parallel Extensions.
I have the following class that both does the execution and provides the results:
public class Step
{
public string Name { get; set; }
public TimeSpan Duration { get; set; }
public bool Completed { get; set; }
public void Execute()
{
DateTime before = DateTime.Now;
RemotedService.DoSomeStuff();
Duration = DateTime.Now - before;
Completed = true;
}
}
How can I process these steps and also save them to a file, in order, after they are processed? I would like to save them to a file while RemotedService.DoSomeStuff()
is waiting for a response from the server.
Writing to the file would be like this:
using (StreamWriter w = File.AppendText("myFile.txt"))
{
var completedStep = completedSteps.Dequeue();
w.WriteLine(string.Format("Completed {0} with result: {1} and duration {2}",
completedStep.Name,
completedStep.Completed,
completedStep.Duration));
}
One option that comes to mind is to add them to a Queue
and have a Timer
that processes them. But this doesn't take advantage of the downtime of the remoted calls.
Another option that comes to mind is to asynchronously write each result to the file using a System.Threading.Tasks.Task
per Step
, but that doesn't guarantee that they will be saved in order and may also introduce contention with writing to the file.