C# 从方法捕获慢速输出

C# 从方法捕获慢速输出,c#,C#,我有一个运行缓慢的实用程序方法,它一次记录一行输出。我需要能够输出这些行中的每一行,然后从代码中的其他位置读取它们。我尝试使用类似于以下代码的任务和流: public static Task SlowOutput(Stream output) { Task result = new Task(() => { using(StreamWriter sw = new StreamWriter(output)) { for(

我有一个运行缓慢的实用程序方法,它一次记录一行输出。我需要能够输出这些行中的每一行,然后从代码中的其他位置读取它们。我尝试使用类似于以下代码的任务和流:

public static Task SlowOutput(Stream output)
{
    Task result = new Task(() =>
    {
        using(StreamWriter sw = new StreamWriter(output))
        {
            for(var i = 0; i < int.MaxValue; i++)
            {
                sw.WriteLine(i.ToString());
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
但是当然,
sr.ReadLine()
总是空的,因为只要调用方法的
sw.WriteLine()
,它就会将底层流的位置更改到末尾

我试图做的是通过将方法输出的字符排队,然后从方法外部使用这些字符,来管道化流的输出。溪流似乎不是前进的方向


有没有一种普遍接受的方法可以做到这一点?

我要做的是切换到一个新的模式

公共静态任务SlowOutput(阻塞收集输出)
{
返回任务。运行(()=>
{
对于(变量i=0;i
消耗

var bc = BlockingCollection<string>();
SlowOutput(bc);
foreach(var line in bc.GetConsumingEnumerable()) //Blocks till a item is added to the collection. Leaves the foreach loop after CompleteAdding() is called and there are no more items to be processed.
{
    Console.WriteLine(line)
}
var bc=BlockingCollection();
SlowOutput(bc);
foreach(bc.getconsumineGenumerable()中的var行)//阻塞,直到将项添加到集合中。在调用CompleteAdding()后离开foreach循环,并且没有其他要处理的项。
{
控制台写入线(行)
}

它必须是流吗?我会使用blockingqueueNo,它不一定是流。谷歌blockingqueueWhat's Driven,即,这里的要求是什么?你只是在尝试流吗?
System.Collections.Concurrent.BlockingCollection
是全名,仅供参考,你几乎不应该使用
新Task(
除非您正在编写自定义任务计划程序,否则请使用
task.Run(
)。
public static Task SlowOutput(BlockingCollection<string> output)
{
    return Task.Run(() =>
    {
        for(var i = 0; i < int.MaxValue; i++)
        {
            output.Add(i);
            System.Threading.Thread.Sleep(1000);
        }
        output.Complete​Adding();
    }
}
var bc = BlockingCollection<string>();
SlowOutput(bc);
foreach(var line in bc.GetConsumingEnumerable()) //Blocks till a item is added to the collection. Leaves the foreach loop after CompleteAdding() is called and there are no more items to be processed.
{
    Console.WriteLine(line)
}