Solved

Proper way to exit a WinForms Application.

Posted on 2009-05-04
14
1,813 Views
Last Modified: 2013-11-26
I am curious about some of the ways others exit their WinForms apps.  For my application, I have a form that is similar to a splash screen that displays initially...gathers some parms from other systems, displays info and allows the user to continue.  At that point the users are at the Main Form, and if it closes, I want everything else to stop, be cleaned up and exit.

I have read about Application.Exit() and Environment.Exit(0), but I am not sure I really want to use either.  I don't really have to many forms and I only will have 3 additional threads running at any given time through the use of BackgroundWorkers.  I was looking at having references to the open forms in the main form and just checking those on Form.Closing()...

I am just curious what some other thoughts are and maybe lessons learned...  I will split the points between the top 2 selected.  Any links you want to provide are appreciated, as I have no trouble reading on my own.

Thanks...
0
Comment
Question by:rgn2121
  • 4
  • 4
  • 3
  • +2
14 Comments
 
LVL 15

Expert Comment

by:JackOfPH
ID: 24301833
0
 
LVL 15

Assisted Solution

by:JackOfPH
JackOfPH earned 150 total points
ID: 24301849
0
 
LVL 13

Expert Comment

by:drypz
ID: 24301857
Your main form is an object of type System.Windows.Forms.Form. Use its Close method to exit the application. In eitherway, you can also use the Dispose or Exit method.
0
 
LVL 15

Expert Comment

by:JackOfPH
ID: 24301862
Musta pre?
0
 
LVL 12

Author Comment

by:rgn2121
ID: 24301888
reading the links...
drypz:
Closing my main form, does not close the application...unless I were to use something like application.Exit in that event.
0
 
LVL 12

Author Comment

by:rgn2121
ID: 24301911
Okay...thanks for the links.  I had already read through the first 2, which prompted me to post the question.  Seems like Application.Exit() is for WinForms, but that it didn't stop and dispose of the threads running outside the main thread.  
Environment.Exit(0) was said to be used for Console apps, but some used it to cancel there threads but it just wouldn't always exit the app.
In the past I have used the Application.Exit() in my Form_Closing() event of my main Form, but I have more threads running then I did then and I want to make sure that I get everything cleaned up.  I guess closing the windows is really the least of my worries...
0
 
LVL 13

Expert Comment

by:drypz
ID: 24301994
Hi jack! Fine.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 48

Expert Comment

by:jpaulino
ID: 24302069
In your FormClosing event, after call the Application.Exit, you can check if your threads are alive and abort them. Without this the application will only finish completely when all threads come to the end.
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        Try
 

            If myThread.IsAlive Then myThread.Abort()
 

        Catch ex As Exception

            ' Ignore any error

        End Try

    End Sub

Open in new window

0
 
LVL 15

Expert Comment

by:JackOfPH
ID: 24302150
jpaulino,

Can the asker use Application.ExitThread instead of
If myThread.IsAlive Then myThread.Abort ?

Is there any difference?

 Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
 
          Application.ExitThread
 
        Catch ex As Exception
            ' Ignore any error
        End Try
    End Sub
0
 
LVL 12

Author Comment

by:rgn2121
ID: 24302284
jpaulino:
I generally use BackgroundWorkers since I know exactly when I need those additional threads and how many I could use at any given time.  The only way I know to kill them is in the in the DoWork event and do e.Cancel...
Is there another way?  Right now if the app is closing and the worker is busy I do  the Worker.CancelAsync() which should then get caught in the DoWork event the next time CancellationPending is checked.
Is there a better idea for those other than switching to using my own threads and using Thread.Start and the Join, Abort to kill?
0
 
LVL 48

Accepted Solution

by:
jpaulino earned 350 total points
ID: 24302427
>> Can the asker use Application.ExitThread instead of

Application.ExitThread will close all the windows on that thread, not the background thread.
Here's an example of a thread with delegate to show some information

    Private myThread As Thread
 

    Delegate Sub myDelegate()
 

    Sub threadStart()

        Try
 

            ' Call the delegate

            If Me.InvokeRequired Then

                Me.Invoke(New myDelegate(AddressOf threadWork))

            End If
 

        Catch ex As ThreadAbortException

            Debug.WriteLine("The was stopped!")

        End Try

    End Sub
 

    Sub threadWork()
 

        ' Do a loop and check if the thread was canceled

        For x As Integer = 0 To 10000

            If Not myThread.IsAlive Then Exit For

            Debug.WriteLine(x.ToString)

            Thread.Sleep(50)

            Application.DoEvents()

        Next
 

    End Sub
 
 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 

        ' Start the thread

        myThread = New Thread(AddressOf threadStart)

        myThread.Priority = ThreadPriority.Normal

        myThread.IsBackground = True

        myThread.Start()
 

    End Sub
 
 

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
 

        ' Check if the thread are running

        If myThread.IsAlive Then

            myThread.Abort()

            myThread.Join()

        End If
 

    End Sub

Open in new window

0
 
LVL 48

Expert Comment

by:jpaulino
ID: 24302442
rgn2121,
can you show some example ?
0
 
LVL 12

Author Comment

by:rgn2121
ID: 24302473
I have quickly written a sample...let me know if you need more...
The code at the bottom is something like what I currently use in my Form_Closing event...

'At the top of a form..

Private WithEvents ExportWorker as New BackgroundWorker
 

'Calling the worker...

Dim objParms = Object

objParms = 'Something I need to use within the thread.

ExportWorker.RunWorkerAsnyc(objParms)
 

'Inside the DoWork Event...

'Some code with a check to see if the user or something else wants to cancel the worker.

If ExportWorker.CancellationPending() then

 e.Canel=True

Else

'Some code

End If
 

'++++ How I cancel in the Form_Closing()  ++++

If ExportWorker.IsBusy() then

  ExportWorker.CancelAsnyc()

  ExportWorker.Dispose()

End if

Open in new window

0
 
LVL 18

Expert Comment

by:carlnorrbom
ID: 24302554
Hi,

I'm not sure about the background workers, but regular threads have a "IsBackground" property that, if set to true, will automatically dispose the running thread if the thread from which it was spawned is disposed. Basically the CLR will invoke .Abort() on the thread if it is still running if you dispose of the main foreground thread.

Dim myThread As New Threading.Thread(New Threading.ThreadStart(AddressOf SomeFunction))
myThread.IsBackground = True

/Carl.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now