停止执行方法c#

时间:2014-08-06 09:36:52

标签: c# wpf methods

单击按钮后,如何才能停止执行方法?

  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

        }


    }

单击停止按钮时,如何结束 public void foreach 。我想在没有关闭我的申请的情况下点击停止时停止下载或提取文件等。

我尝试过使用返回,但会继续执行(下载/解压缩等)。

5 个答案:

答案 0 :(得分:2)

你无法停止执行单个方法。你可以通过使用线程来使用它。 使用新线程运行该方法,并在按钮单击信号时停止该线程。 看看这个帖子 - C# Threading - How to start and stop a thread http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx

答案 1 :(得分:0)

停止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(.....
}

答案 2 :(得分:0)

快速而肮脏的解决方案可能是为变量引入测试,并通过按停止按钮设置此变量。请注意,这只适用于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,Dispatcher会创造奇迹。请参阅http://msdn.microsoft.com/en-us/magazine/cc163328.aspx

答案 3 :(得分:0)

取消工作线程执行的最规范技术是称为协同取消的模式。 MSDN has a nice article on it。请注意,这与使用基于任务的异步编程有关。

要点与此类似:

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为真时取消操作。

答案 4 :(得分:0)

我不习惯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();
}