Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I have a requirement like i need to open 4 child windows with the help of main (parent) window. In main window i have a combo box it has 4 list items. When i select any one of them it will open a new window. Suppose combo box having options like 1,2,3,4 when i select 1 form that it will displayed first window and whatever the code will be executed while executing the first one i need to open simultaneously second one. I am able to close the child window but background the thread is still running. I have different ways but i am not able to kill the thread process. How can i kill the process and close the form. Thanks in an advance...

Regards,
Jeevan.
Posted
Comments
Herman<T>.Instance 2-Mar-12 10:10am    
read this.

You can use a BackgroundWorker and add support in your worker code for cancellation. Read this article[^] for an example.
 
Share this answer
 
To make it a little more straight forward, look at the following code:
C#
static void Main(string[] args)
{
    var bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.WorkerSupportsCancellation = true;
    bw.RunWorkerAsync();
    bw.CancelAsync();
    Console.ReadLine();
}

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
    var bw = (BackgroundWorker) sender;
    while (!bw.CancellationPending)
    {
        //do work here
    }
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
    else
    {
        bw.ReportProgress(100);
    }
}
 
Share this answer
 
Also add an event handler for FormClosing. If the background thread is running, cancel it, set a flag in the form to remember you want to close it later and cancel the form closing event.

When the background thread complete, check the flag and if the flag is set, then close the form at this point.

This works quite well if the cancellation does not take much time. Otherwise, you might want to hide the form before closing it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900