[英]Pass StreamWriter to another thread and close the thread after N seconds
我有这样的代码:
StreamWriter successWriter = File.AppendText(pathSuccess);
task = Task.Factory.StartNew(() =>
{
IEnumerable<string> lines = File
.ReadLines(actualPath)
.Skip(GetInt(positionNumericUpDown.Value));
try
{
var options = new ParallelOptions()
{
CancellationToken = cts.Token,
MaxDegreeOfParallelism = GetInt(maxThreadNumericUpDown.Text)
};
Parallel.ForEach<string>(lines, options, (line, loopState, idx) =>
{
options.CancellationToken.ThrowIfCancellationRequested();
Result result = getResult(line);
lock(successWriter)
{
successWriter.WriteLine("{0}\t{1}", result.Url, result.Message);
successWriter.Flush();
}
}
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
},
TaskCreationOptions.LongRunning);
现在我需要每 60 秒用方法启动另一个线程NewThread
void checkForMoreResults(successWriter);
NewThread可能需要超过 60 秒,因此我需要在启动新线程之前关闭先前运行的线程(每 60 秒后)
任何建议我该怎么做都将不胜感激
为什么不直接使用BackgroundWorker并调用CancelAsync ()? 它可能比 .net TPN API 更容易一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.