Shifty
Shifty

Reputation: 13

How do I return results while inside a loop in C#?

Essentially, I have a Do..While loop going through some lines from a text file. I want to process a line, return a value (worked or didn't), then move to the next line.

I have a function called ProcessTXT that accepts 2 strings. Source and Destination of new file.

Is there a way to set a ReturnedValue string = to the result and have the backgroundworker check to see if the variable changed? And if so, add this value to the list box?

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

EDIT: Current test code using Yield. My output is "TestingGround.Form1+d__0". Did i do something wrong?

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

    }
}

Upvotes: 1

Views: 2039

Answers (2)

Servy
Servy

Reputation: 203827

It sounds like this is a good case for a producer/consumer queue. C# 4.0 introduced BlockingCollection, which is great for this. Create the blocking collection and ensure that both this process, and whatever needs to consume the results you are passing have access to it. This method can add items to the queue, and whatever is reading the results can use the Take method, which will block [wait] until there is at least one item to take out. The collection is specifically designed to work in multithreaded environments; all of the operations are logically atomic.

Upvotes: 2

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Yield is typically used to return results iteratively, or streaming. There are plenty of examples online. There's one on SO for reading in a file.

Upvotes: 5

Related Questions