简体   繁体   中英

Stop running method in thread when close form

i have a problem with my code. Im creating a graphic app that have a main form. When i click on a button i create a new form that show a progress bar while export some files. My problem start when i try to close the form with the progress bar because method what export files doesnt end.

In the new form, i execute a method that check the progress of the export and fill the progress bar, this method is executed each second. To export i create a new thread, and this thread execute the export method.

If the export finish, form and thread close right way but if i "force" stop operation by closing the form, the thread that are exporting doesnt stop until the export ends or when i close the main form.

So, how can i stop that thread?

This is my code:

 public Form3(File file, string output, string inputFile)
    {
        InitializeComponent();
        this.file = file;
        this.output = output;
        this.inputFile = inputFile;
        progressLabel.Location = new Point(textProgress.Right, progressLabel.Top);
        thread = new Thread((ThreadStart)delegate { Exporter.ExportToFile(this.file, this.output, this.inputFile); });
        thread.IsBackground = true;
        thread.Start();

        TimerControl();


    }

    private void TimerControl()
    {
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        t.Tick += new EventHandler(GetProgress);
        t.Interval = 1000; // in miliseconds
        t.Start();    

    }

    private void GetProgress(object sender, EventArgs myEventArgs)
    {
        int x = Exporter.GetProgress();
        progressBar.Maximum = 100;
        if (!Exporter.stop)
        {
            progressBar.Value = x;
            progressLabel.Text = x.ToString() + "%";
        }
        else
        {

            this.Close();

        }
    }

The thing to understand here: that code that runs that "export to file" ( Exporter.ExportToFile ) ... is probably not written to be stopped.

In other words: you want to enhance that component. If you really mean to use it in such a context, then you definitely want to add another method to your exporter; such as "AbortExport" or something alike!

(instead of just killing the underlying thread for example - you might want to ensure that any file created by that export gets removed for example; and that all associated resources see proper cleanup)

Why not use Tasks instead?

quote from https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

By throwing a OperationCanceledException and passing it the token on which cancellation was requested. The preferred way to do this is to use the ThrowIfCancellationRequested method. A task that is canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request.

quote from https://msdn.microsoft.com/en-us/library/dd997364(v=vs.110).aspx

The general pattern for implementing the cooperative cancellation model is:

  • Instantiate a CancellationTokenSource object, which manages and sends cancellation notification to the individual cancellation tokens.

  • Pass the token returned by the CancellationTokenSource.Token property to each task or thread that listens for cancellation.

  • Provide a mechanism for each task or thread to respond to cancellation.

  • Call the CancellationTokenSource.Cancel method to provide notification of cancellation.

See the sample code at the 1st article

You can use the Thread.Abort(); method , but it is not the optimal/safest way to abort a thread .

The safest way to exit a thread is to add extra code in your exporter class to exit at the right time ..

You can find tons of answers on stackoverflow that agrees with me that threads should be exited safely by user code ..

EDIT : using the Thread.Abort(); is a bad idea , i thought it was clear in the original answer

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