Reputation: 549
I am making an app that is used to sort lines from a csv into one of four categories. The app reads the csv, displays a line, and waits for the user to select which category the line belongs in by pressing a button (one for each category) before reading the next line.
What I tried was:
using (StreamReader reader = new StreamReader(inputFile))
{
reader.ReadLine(); // skip first line
string line;
while ((line = reader.ReadLine()) != null)
{
// Display line
proceed = false;
while (!proceed) { } // wait for user input
}
}
And on category select button press 'proceed' would be changed to true. The problem is this just locks the entire program up and you can't press any buttons.
How can I achieve the same functionality?
Upvotes: 1
Views: 1133
Reputation: 760
As you said, the while (!proceed)
loop is blocking your program. One possible solution is to use another thread to process the CSV file, so that the user interface remains responsive. First of all, create an AutoResetEvent
property that will be used to communicate to the new thread that the user gave an input and it's time to continue doing its stuff:
AutoResetEvent waitInput = new AutoResetEvent(false);
Now create a new method to process the CSV file, that will be run on a separate thread:
private void ReadAllLines()
{
using (StreamReader reader = new StreamReader(inputFile))
{
reader.ReadLine(); // skip first line
string line;
while ((line = reader.ReadLine()) != null)
{
waitInput.WaitOne(); // wait for user input
// Do your stuff...
}
}
}
At this point, when you want to start processing the CSV file, create a new thread and start it:
// The new thread will run the method defined before.
Thread CSVProcessingThread = new Thread(ReadAllLines);
CSVProcessingThread.Start();
There is one last action to do in order for the program to work properly: we have to tell the new thread when the user gave an input, otherwise the new thread will keep waiting for user input without doing anything (but your main thread will continue working normally). When you want to communicate that the new thread has to continue doing its work, insert this line into code:
waitInput.Set();
In your scenario, you should insert this line in the button click event handler, so that when the user clicks the button to continue processing the CSV file, the newly created thread will continue processing the file as defined in the ReadAllLines()
routine.
Upvotes: 1