Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 549993
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:14:31+00:00 2026-05-13T11:14:31+00:00

I got a .net WinForms application. I have a UserControl which gets instantiated based

  • 0

I got a .net WinForms application. I have a UserControl which gets instantiated based on user action – upon instantiation, it performs some time-consuming tasks on a background thread (using BackgroundWorker), while displaying the ajaxy spinning animation. The user can click away at anytime, then click back onto the user control (which would start the background thread all over again).

When the user clicks away, I want to dispose of the UserControl and all the resources that it holds (including the background thread). What is the best way of doing this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:14:32+00:00Added an answer on May 13, 2026 at 11:14 am

    Call the CancelAsync method on the BackgroundWorker and wait for it to terminate. Construct your worker code so that it frequently checks for the cancel flag.

    If there are no negative side effects if the thread continues to run for a while, and it will in no way reference the User Control or any resource held by it, you can dispose of the User Control after requesting the thread to terminate.

    EDIT: Demo code

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public partial class FrmMain : Form
        {
            public FrmMain()
            {
                InitializeComponent();
            }
    
            private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                MessageBox.Show("BG Done");
            }
    
            private void btnStart_Click(object sender, EventArgs e)
            {
                bg.WorkerSupportsCancellation = true;
                bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
                bg.DoWork += new DoWorkEventHandler(bg_DoWork);
                bg.RunWorkerAsync();
            }
    
            void bg_DoWork(object sender, DoWorkEventArgs e)
            {
                int i=0;
    
                while (!bg.CancellationPending)
                {
                    lblStatus.BeginInvoke((MethodInvoker) delegate { lblStatus.Text = i + " sec."; });
                    System.Threading.Thread.Sleep(1000);
                    i++;
                }
    
                lblStatus.BeginInvoke((MethodInvoker)delegate { lblStatus.Text = "CANCEL"; });
            }
    
            private void btnStop_Click(object sender, EventArgs e)
            {
                bg.CancelAsync();
                while (bg.IsBusy) // For real code limit max wait time in while loop
                {
                    System.Threading.Thread.Sleep(50);
                    Application.DoEvents();
                }
                this.Close();
            }
        }
    }
    
    
    namespace WindowsFormsApplication1
    {
        partial class FrmMain
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.bg = new System.ComponentModel.BackgroundWorker();
                this.btnStart = new System.Windows.Forms.Button();
                this.btnStop = new System.Windows.Forms.Button();
                this.lblStatus = new System.Windows.Forms.Label();
                this.SuspendLayout();
                // 
                // bg
                // 
                this.bg.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bg_RunWorkerCompleted);
                // 
                // btnStart
                // 
                this.btnStart.Location = new System.Drawing.Point(39, 13);
                this.btnStart.Name = "btnStart";
                this.btnStart.Size = new System.Drawing.Size(75, 23);
                this.btnStart.TabIndex = 0;
                this.btnStart.Text = "Start";
                this.btnStart.UseVisualStyleBackColor = true;
                this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
                // 
                // btnStop
                // 
                this.btnStop.Location = new System.Drawing.Point(39, 42);
                this.btnStop.Name = "btnStop";
                this.btnStop.Size = new System.Drawing.Size(75, 23);
                this.btnStop.TabIndex = 1;
                this.btnStop.Text = "Stop";
                this.btnStop.UseVisualStyleBackColor = true;
                this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
                // 
                // lblStatus
                // 
                this.lblStatus.AutoSize = true;
                this.lblStatus.Location = new System.Drawing.Point(39, 72);
                this.lblStatus.Name = "lblStatus";
                this.lblStatus.Size = new System.Drawing.Size(73, 13);
                this.lblStatus.TabIndex = 2;
                this.lblStatus.Text = "(Not Running)";
                // 
                // FrmMain
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(423, 136);
                this.Controls.Add(this.lblStatus);
                this.Controls.Add(this.btnStop);
                this.Controls.Add(this.btnStart);
                this.Name = "FrmMain";
                this.Text = "Main";
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
    
            private System.ComponentModel.BackgroundWorker bg;
            private System.Windows.Forms.Button btnStart;
            private System.Windows.Forms.Button btnStop;
            private System.Windows.Forms.Label lblStatus;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created a .NET C# WinForms application on Win 7 RTM x64, which
I've got a VB.NET WinForms app in which I have the need to refer
I've got a .NET 2.0 Windows desktop application (time-sheets) which i develop and wanted
I've got a vertical market Dot Net Framework 1.1 C#/WinForms/SQL Server 2000 application. Currently
I've got a asp.net mvc application with session state enabled (sqlSessionProvider). End user will
We have got a .NET application (VB / VS2010) and the project has been
I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding
C# / .NET 3.5 / WinForms I've got a form that opens a modal
I've got a .NET application that uses Remoting between an Administration Console and a
I've got a .NET 3.5 web application written in C# doing some URL rewriting

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.