我想知道使用.NET 4.0 Parallel Extensions在低优先级线程上串行处理长时间运行进程结果的最佳方法。
我有以下类既执行执行又提供结果:
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;
}
}
在处理完这些步骤后,如何按顺序将它们保存到文件中?我想在RemotedService.DoSomeStuff()
等待服务器响应时将它们保存到文件中。
写入文件将如下所示:
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));
}
想到的一个选择是将它们添加到 aQueue
并让 aTimer
处理它们。但这并没有利用远程调用的停机时间。
想到的另一个选择是使用System.Threading.Tasks.Task
per将每个结果异步写入文件Step
,但这并不能保证它们会按顺序保存,并且还可能会引入写入文件的争用。