等待用户输入以在 c# winforms 中继续 StreamReader
Wait for user input to continue StreamReader in c# winforms
我正在制作一个应用程序,用于将 csv 中的行分类为四个类别之一。该应用程序读取 csv,显示一行,并在阅读下一行之前等待用户通过按下按钮(每个类别一个)select 该行属于哪个类别。
我试过的是:
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
}
}
并且在类别 select 按钮上按下 'proceed' 将更改为 true。问题是这只会锁定整个程序,您无法按任何按钮。
如何实现相同的功能?
如您所说,while (!proceed)
循环阻塞了您的程序。一种可能的解决方案是使用另一个线程来处理 CSV 文件,以便用户界面保持响应。首先,创建一个 AutoResetEvent
属性 用于与用户提供输入的新线程通信,是时候继续做它的事情了:
AutoResetEvent waitInput = new AutoResetEvent(false);
现在创建一个新方法来处理 CSV 文件,这将是 运行 在单独的线程上:
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...
}
}
}
此时,当你想开始处理CSV文件时,新建一个线程并启动它:
// The new thread will run the method defined before.
Thread CSVProcessingThread = new Thread(ReadAllLines);
CSVProcessingThread.Start();
为了使程序正常运行,还有最后一个操作要做:我们必须在用户输入时告诉新线程,否则新线程将继续等待用户输入而不做任何事情(但是您的主线程将继续正常工作)。当您想传达新线程必须继续工作时,将此行插入代码:
waitInput.Set();
在你的场景中,你应该在按钮点击事件处理程序中插入这一行,这样当用户点击按钮继续处理 CSV 文件时,新创建的线程将继续处理 ReadAllLines()
例程。
我正在制作一个应用程序,用于将 csv 中的行分类为四个类别之一。该应用程序读取 csv,显示一行,并在阅读下一行之前等待用户通过按下按钮(每个类别一个)select 该行属于哪个类别。
我试过的是:
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
}
}
并且在类别 select 按钮上按下 'proceed' 将更改为 true。问题是这只会锁定整个程序,您无法按任何按钮。
如何实现相同的功能?
如您所说,while (!proceed)
循环阻塞了您的程序。一种可能的解决方案是使用另一个线程来处理 CSV 文件,以便用户界面保持响应。首先,创建一个 AutoResetEvent
属性 用于与用户提供输入的新线程通信,是时候继续做它的事情了:
AutoResetEvent waitInput = new AutoResetEvent(false);
现在创建一个新方法来处理 CSV 文件,这将是 运行 在单独的线程上:
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...
}
}
}
此时,当你想开始处理CSV文件时,新建一个线程并启动它:
// The new thread will run the method defined before.
Thread CSVProcessingThread = new Thread(ReadAllLines);
CSVProcessingThread.Start();
为了使程序正常运行,还有最后一个操作要做:我们必须在用户输入时告诉新线程,否则新线程将继续等待用户输入而不做任何事情(但是您的主线程将继续正常工作)。当您想传达新线程必须继续工作时,将此行插入代码:
waitInput.Set();
在你的场景中,你应该在按钮点击事件处理程序中插入这一行,这样当用户点击按钮继续处理 CSV 文件时,新创建的线程将继续处理 ReadAllLines()
例程。