簡體   English   中英

停止執行方法C#

[英]Stop execution of a method c#

單擊按鈕時如何停止執行方法?

  public void ForEach()
    {
        CreateFolders();

        //For each process get the equivalent processcode
        foreach (string item in Processes)
        {
            ItemValue = item;
            //Get process code for the process under the selected source
            GetActiveProcess();

            #region Switch
            switch (ProcessCode)
            {
                #region DownloadFile
                case "Download File":
                    ForDownloadFile();
                    break;
                #endregion

                #region UnzipFile
                case "Unzip File":
                    ForUnzipFile();

                    break;
                #endregion

                #region RenameFile
                case "Rename File":
                    ForRenameFile();
                    break;
                #endregion

                #region MergeFile
                case "Merge File":
                    ForMergeFile();
                    break;
                #endregion

                #region ZipFile
                case "Zip File":
                    ForZipFile();
                    break;
                #endregion

                #region UploadFile
                case "Upload File":
                    ForUploadFile();
                    break;
                #endregion
            }
            #endregion

        }


    }

當我單擊停止按鈕時,如何結束我的公共無效foreach 當我單擊停止而不關閉我的應用程序時,我想停止下載或提取文件等。

我試過使用return,但它會繼續執行(下載/解壓縮等)。

您不能停止執行單個方法。 您可以通過使用線程來使用它。 使用新線程運行該方法,並在單擊按鈕時提示該線程停止。 查看此線程-C#線程-如何啟動和停止線程 http://msdn.microsoft.com/zh-cn/library/7a2f3ay4(v=vs.90).aspx

停止ForEach()應該很容易,但是停止每個Case定義的每個方法取決於您在這種情況下的工作。

// Defined somewhere which is available to you ForEach() and your Stop button.
// In the stop button set the KeepProcessing to false.
bool KeepProcessing = true;   

foreach (string item in Processes)
{
    if(!KeepProcessing)
         return;

    switch(.....
}

快速而骯臟的解決方案可能是對變量進行測試,然后通過按停止按鈕設置該變量。 請注意,這僅適用於WinForm應用程序,對於WPF應用程序,則需要導入system.windows.forms.dll-有效地使其成為非wpf。

例如:

bool stop = false;

foreach (string item in Processes)
{
    if (stop)
        break;

    //do-your-stuff

    Application.DoEvents(); //this will force the winform app to handle events from the GUI
}

//Add an eventhandler to your stop-button
private void stopButton_Click(System.Object sender, System.EventArgs e)
{
    stop = true;
}

但是,正如Rabi所建議的那樣,最好在應用程序中引入一些線程。 對於WPF,調度員會創造奇跡。 請參閱http://msdn.microsoft.com/en-us/magazine/cc163328.aspx

取消工作線程執行的最規范的技術是一種稱為“ 合作取消”的模式。 MSDN上有一篇不錯的文章 請注意,這與使用基於任務的異步編程有關。

要點類似於以下內容:

public void DoWork(IEnumerable<Work> workItems, ref bool cancel)
{
    foreach(thing in workItems)
    {
        //poll to see if you need to abandon the work.
        if(cancel)
            throw new WorkCancelledException(); //or whatever exception you want to use. MSDN shows you a built in one.

        ProcessThing(thing); //process the item. An item is just a unit of work. You dont have to use a collection of work items.
    }
}

按下取消按鈕時,設置取消布爾值。 MSDN示例使用CancellationToken ,我會推薦它。 它不限於Task實現。

為什么要合作? 消費代碼和執行代碼都必須就取消方法達成一致,並在cancel為true時同意取消操作。

我不習慣Wpf,但是我認為如果需要使用線程,則使用BackGroundWorker是正確的解決方案。

https://stackoverflow.com/a/5483644/906404

private readonly BackgroundWorker worker = new BackgroundWorker();

// Initialization code
worker.DoWork += worker_DoWork;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();          // Runs your code in a background thread

private void worker_DoWork(object sender, DoWorkEventArgs e)  
{
    CreateFolders();

    //For each process get the equivalent processcode
    foreach (string item in Processes)
    {

   -->> if (worker.CancellationPending) break;

        ItemValue = item;
        //Get process code for the process under the selected source
        GetActiveProcess();


        ... your code... 

    }
}

void OnClickStopButton(args) {
   worker.CancelAsync();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM