2013-01-09 52 views
2

我有兩個函數 - 一個是在一個循環內的串行端口上運行一些命令,另一個是應該停止第一個方法中循環執行的事件處理程序。這裏是一些示例代碼。C#Break其他函數循環在另一個函數

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.       
    } 
} 

我不知道我該如何做到這一點。

回答

1

設置中斷變量;

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. 
    } 
} 
+0

我必須從我停止按鈕處理這我怎麼能處理它有一個全局變量? –

+3

如果你打算使用一個變量,你至少希望它變成'volatile' –

+0

@Artinos我更新了站點 – TNCodeMonkey

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; 
} 
相關問題