【发布时间】:2015-04-26 16:35:23
【问题描述】:
我正在努力锻炼如何创建一些基本上暂停我的 while 循环直到我按下 button1 的东西,我知道事件处理程序 button1_Click 但我认为这在这种情况下不会起作用,因为我有很多嵌套循环在我的 form_load 上互相访问。
任何帮助将不胜感激!
这是我的代码片段,我希望循环“暂停”并附上注释:
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2["Question Space"]);
label1.Text = QuestionSpace;
if (button1.Click = true) // if the button is clicked)
{
// continue with the while loop (I am going to add an INSERT SQL query in here later)
}
else
{
// pause until the button is pressed
}
}
我的整个表单代码:
public partial class CurrentlySetTestForm : Form
{
private int QuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
MessageBox.Show(y);
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT [QuestionID] FROM QuestionStudentAssociation WHERE ( [StudentID]=@Signedinstudent)", connect);
command18.Parameters.AddWithValue("@Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
QuestionID = Convert.ToInt32(reader["QuestionID"]);
SqlCommand command19 = new SqlCommand(@"SELECT [Question Space] FROM Questions WHERE ( [QuestionID] = @currentQID )", connect);
command19.Parameters.AddWithValue("@currentQID", QuestionID);
try
{
var reader2 = command19.ExecuteReader();
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2["Question Space"]);
label1.Text = QuestionSpace;
if (button1.Click = true) // if the button is clicked)
{
// continue with the while loop (I am going to add an INSERT SQL query in here later)
}
else
{
// pause until the button is pressed
}
}
}
catch (SyntaxErrorException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Done one loop");
}
}
}
}
【问题讨论】:
-
如果您在 UI 线程中阻止执行,UI 将不会响应用户,因此她将无法单击按钮。您可以考虑将后台任务放在后台线程中,并使用使用 Tasks 的 AutoResetEvent。
-
我不是 100% 确定你的意思
-
如果要执行阻塞代码,则需要在UI线程以外的线程中执行。
-
对不起,我不太了解 UI 线程是什么,您能否在答案中给我一个小例子?
-
尝试阅读multi threading。要在不为线程问题困扰的情况下修复代码,请尝试编写代码以使用事件处理程序,而不是通过 while 循环的轮询机制。
标签: c# loops button while-loop nested-loops