简体   繁体   中英

Stop execution of a method c#

How can I able to stop the execution of my method when I click a button?

  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

        }


    }

How can I end my public void foreach when I click the stop button. I would like to stop the downloading, or extracting of file etc when ever I click on stop without closing my application.

I've tried using return but it continues to execute (Download/ extract etc).

you cant stop execution of a single method. you can use it by using threads . Use a new thread to run the method and on button click signal the thread to stop . look at this thread - C# Threading - How to start and stop a thread http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx

Stopping your ForEach() should be easy, but stopping each method you have defined per Case depends on what you're doing in that 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(.....
}

The quick and dirty solution could be to introduce a test for a variable, and set this variable by pressing the stop button. Please note that this will only work for a WinForm application, for a WPF application, you would need to import system.windows.forms.dll - effectively making it non-wpf.

For example:

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

But, as suggested by Rabi, it would be much better to introduce some threading to your application. For WPF, a Dispatcher would do wonders. Please see http://msdn.microsoft.com/en-us/magazine/cc163328.aspx .

The most canonical technique for cancelling execution of a worker thread is a pattern called Cooperative Cancellation . MSDN has a nice article on it . Note that this relates to using Task based asynchronous programming.

The gist is similar to this:

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

When your cancel button is pressed, set the cancel boolean. The MSDN example uses a CancellationToken and i would recommend it. It is not limited to Task implementations.

Why is it cooperative? Both the consuming code and the executing code have to agree on the method of cancellation and agree to cancel the operation when the cancel is true.

I'm not used to Wpf, but I think that using a BackGroundWorker is a right solution if you need to use a thread.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM