将StreamWriter传递给另一个线程,并在N秒后关闭线程

时间:2011-04-28 09:19:33

标签: c# multithreading

我有这样的代码:

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秒一次)

任何建议我该怎么做才会赞赏

1 个答案:

答案 0 :(得分:0)

为什么不使用 BackgroundWorker 并调用 CancelAsync ()?它可能比.net TPN API更容易一些。