1

本质上,我有一个Do..While循环遍历文本文件中的一些行。我想处理一行,返回一个值(工作或没有),然后移动到下一行。

我有一个ProcessTXT接受 2 个字符串的函数。 SourceDestination新文件。

有没有办法为ReturnedValue string =结果设置 a 并让后台工作人员检查变量是否更改?如果是这样,将此值添加到列表框中?

private void TranslatePOD(string strSource, string strDest,)
{
  TextWriter tw = new StreamWriter(strDest);
  TextReader tr = new StreamReader(strSource);
  do
    {
      //My Code doing stuff
      //Need to send a result somehow now, but i have more work to do in this loop
      //Then using tw.writeline() to write my results to my new file
    } while (tr.ReadLine() != null);
}

编辑:当前使用 Yield 的测试代码。我的输出是“TestingGround.Form1+d__0”。我做错什么了吗?

namespace TestingGround
{
public partial class Form1 : Form
{
    static IEnumerable<string> TestYield(string strSource) 
    {
        TextReader tr = new StreamReader(strSource);
        string strCurLine = System.String.Empty;

        while ((strCurLine = tr.ReadLine()) != null)
        {
            yield return strCurLine;
        }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string MySource = System.String.Empty;
        MySource = @"C:\PODTest\Export Script\Export\Shipment List.csv";
        listBox1.Items.Add(TestYield(MySource));

    }
}
4

2 回答 2

5

Yield通常用于迭代或流式返回结果。网上有很多例子。SO上有一个用于读取文件。

于 2012-08-17T19:30:01.730 回答
2

听起来这对于生产者/消费者队列来说是一个很好的案例。引入了 C# 4.0 BlockingCollection,对此非常有用。创建阻塞集合并确保此过程以及任何需要使用您传递的结果的东西都可以访问它。该方法可以将项目添加到队列中,任何正在读取结果的都可以使用该Take方法,该方法将阻塞[等待],直到至少有一个项目可以取出。该集合专为在多线程环境中工作而设计;所有操作在逻辑上都是原子的。

于 2012-08-17T19:36:30.410 回答