从方法

时间:2017-07-05 16:01:33

标签: c#

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

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);
            }
        }
    }
}

然后这样叫:

MemoryStream ms = new MemoryStream();
var t = SlowOutput(ms);
using (var sr = new StreamReader(ms))
{
    while (!t.IsCompleted)
    {
        Console.WriteLine(sr.ReadLine())
    }
}

但当然,sr.ReadLine()始终为空,因为只要调用方法的sw.WriteLine(),它就会将基础流的位置更改为结尾。

我要做的是通过排队方法输出的字符然后从方法外部消耗它们来管道流的输出。流似乎不是一种可行的方式。

有普遍接受的方法吗?

1 个答案:

答案 0 :(得分:0)

我要做的是切换到BlockingCollection<String>

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)
}
相关问题