将 StreamWriter 传递给另一个线程并在 N 秒后关闭该线程
我有这样的代码:
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 秒后)
任何建议我该怎么做将不胜感激
I have code like this:
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);
Now I need every 60 seconds start another thread NewThread with method
void checkForMoreResults(successWriter);
The NewThread can take more than 60 seconds so I need close the previosuly running thread before starting the new one (after every 60 seconds)
Any suggestion how can I do it will appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不直接使用 BackgroundWorker 并调用 CancelAsync() 呢?它可能比 .net TPN API 更容易一些。
why not just use BackgroundWorker and call CancelAsync()? it might be a little bit easier perhaps than the .net TPN APIs.