2

我有两个功能 - 一个是在循环中在我的串行端口上运行一些命令,另一个是一个事件处理程序,它应该在第一种方法中停止循环的执行。这是一些示例代码。

public void btm_Processing_Click(object sender, EventArgs e)
{   
    for (int i = 1; i <= x ; i++)
    {
        // My processing commands are here .
    }
}

这是我的停止按钮事件处理程序。

private void btm_Stop_Click(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Do you want to stop processing?",
                                       "Error",
                                       MessageBoxButtons.YesNo);

    if (dialogResult == DialogResult.Yes)
    {
        // Here is where I want to break that loop.                
    }
    else
    {
        // Do other things.                           
    }
}

我不确定我该怎么做。

4

2 回答 2

4

最好的方法是使用 BackgroundWorker 线程来执行你的循环,然后你可以稍后从主线程中取消它。

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

更简单的方法是制作您设置的全局变量

private volatile bool isWorking = false;
public void btm_Processing_Click(object sender, EventArgs e)
{
    isWorking = true;
    for (int i = 1; i <= x ; i++)
    {
        //My Processing Commands are Here 
        if(!isWorking)
            break;
    }
}

private void btm_Stop_Click(object sender, EventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Do You Want To Stop Processing ? ", "Error", MessageBoxButtons.YesNo);
    isWorking = dialogResult != DialogResult.Yes;
}
于 2013-01-09T01:15:51.100 回答
2

设置中断变量;

private volatile bool shouldStop = false;

private void btm_Processing_Click(object sender, EventArgs e)
{          
    for (int i = 1; i <= x ; i++)
    {
        //My Processing Commands are Here 

        if (shouldStop)
        {
            shouldStop=false;
            break;
        }
    }
}

private void btm_Stop_Click(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Do you want to stop processing?",
                                       "Error",
                                       MessageBoxButtons.YesNo);

    if (dialogResult == DialogResult.Yes)
    {
        shouldStop = true;                
    }
    else
    {    
        // Do other things.
    }
}
于 2013-01-09T01:12:37.990 回答