Solved

Proper way to exit a WinForms Application.

Posted on 2009-05-04
14
1,830 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

733 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