In the past I've usually added the following line to the KeyDown sub in order to end my applications:
If e.KeyCode = Keys.Escape Then End
However, upon reading the documentation on what End actually does, it turns out that it probably is one of the worst ways to end the application in terms of releasing resources, etc.
So now I'm trying to find the recommended way to terminate the application which will properly handle all resources, etc. I've found these two questions on SO (here and
here) but I can't conclude what the right answer actually is.
The accepted answer on the first link says that applying Close() to all forms is the correct way and will release all resources used correctly. This isn't convenient in applications with multiple forms, and further down Application.Exit() is suggested, and even:
Application.Exit()
End
which will definitely make sure the program ends even if the first line fails.
On the other hand, the accepted answer on the second link says "you should never have to call Application.Exit() in a properly-designed application", contradicting the above and an answer further down which says Application.Exit() calls Close() on all forms in later versions of .Net.
This has lead me to confusion — what is wrong with Application.Exit()?
If there is no problem with it, then am I right in thinking the best one to go with is:
Application.Exit()
End
or is that overdoing it? Otherwise, when does Application.Exit() fail to work (except when I write code which cancels it)?
Note: Although this question applies to all programs I make, including ones with multiple forms, I recently have started using Sockets (with the TcpClient/Listener classes) to make connections between computers and would appreciate any additional information relating to this when terminating the program in the middle of a connection. A comment in my recent question assures me that calling Socket.Close() isn't even necessary, but now I realise that this may not be completely true since I was using End to terminate before.
Application.Exit posts an exit message to all message loops for that application.
It's a perfectly acceptable way of closing an application and will cause all forms to attempt to shutdown. Individual forms can override this behaviour, for instance if they have unsaved work. This will leave your application running afterward so you need to decide if that needs to be handled.
Saying that I only use it if an external actor needs to shutdown my application. Otherwise I leave the app to exit when its main form closes.
You also need to consider the state of any foreground threads you have as these can allow all your forms to close but leave the thread processing in the background.
End is a very brute force technique and should be used as a last resot. A well designed application should be able to shutdown by closing the forms or by calling application.exit. I have used the approach in the past of launching a timer which will call End just before I call Application.Exit ... at least I give it a chance to complete gracefully.
Note: Application.Exit doesn't block. So Application.Exit : End might as well be End which is not ideal.
Here's the timer I use:
Dim forceExitTimer = New Threading.Timer(Sub() End, Nothing, 2500, Timeout.Infinite)
Application.Exit()
Related
I am new to vb.net and have a project that I have made my first windows service. Now I have a function that retrieves a count of transactions. I would like to call that function and put the results in a text file. I can hard code a stream to put into the text file, but whenever I call the function, the services just crashes. Not errors just dies. What am I doing wrong?
I have tried coding the function inside of the service-nope
I coded the function in a separate class-Nope! dies when I call it
Private Sub BrowserMailSender(obj As Object, e As EventArgs)
Try
FileIO.WriteToFile("service is started:" + Now + vbNewLine)
My_Count() 'service dies here
FileIO.WriteToFile("end" + vbNewLine)
Catch ex As Exception
MsgBox(ex)
End Try
the function works if I call from the main project but I would like the service to run and save the data behind the scenes.
The call to MsgBox is at the root of the problem. A Windows Service runs in a context where it does not have the ability to present a User Interface to the user. You'll have to find another way to communicate errors, such as the Event Log or a log file.
Prior to Vista, the line between services and the user was permeable, partly because the OS wasn't yet designed to keep them isolated, and partly because most users ran with full administrative privileges all the time. From Vista forward, you have to work "in the dark".
There are ways present a UI to the user, and one of the answers here briefly mentions one of them. However, I would caution you against trying to present a UI at all. The main principle of a service is that it sits in the background and does things without requiring the user to interact with it. Presenting a UI for events that the user is not aware are happening at that moment is an asymmetrical relationship. It could block your service indefinitely when a user isn't expecting to have to interact with it to allow it to continue.
I tried this to show some MsgBox when shutdown or logoff is detected.. like "You're logging off.. .
Public Class frmDetectEnd
Private Sub frmDetectEnd_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf Handler_SessionEnding
End Sub
Public Sub Handler_SessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
MessageBox.Show("User is logging off")
ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
MessageBox.Show("System is shutting down")
End If
End Sub
End Class
This detection work's OK but I want to stop shutdown/logoff process if MsgBox is shown, because at this point the shutdown/logoff process is executed and it stops with Windows message "This program is preventing to log you off...".
However, I would like that after getting message "User is logging of/System is shutting down" the user can select command button to proces something and then Shutdown or LogOff can continue.
It's pretty much impossible to cancel a shutdown/logoff after it has started. At most you can get the "This program is preventing Windows from shutting down" message, like you said in your question.
A potential solution would be to create system-wide hooks for the InitiateShutdown, InitiateSystemShutdown and InitiateSystemShutdownEx functions (requires C++ or some other kind of low-level language). However, they would need to be coded carefully and tested thoroughly, and even if you managed to get them working most of the times, there's no guarantee that the OS isn't bypassing them via some other, even deeper functions (it contains a lot of both undocumented and name-mangled functions).
Source:
I researched this heavily about two years back in an attempt to make a program that would completely block system shutdown if the user chose to. However, as mentioned above, it has proven to be extremely difficult, if not impossible. None of my attempts were a success.
You could immediately call shutdown /a when a shutdown is detected. (/a stands for "abort").
That's a built-in command-line utility in Windows, so you'd call it the usual way of calling command-line utilities within a vb app. The trick is it has to happen fast enough.
Another more hacky way you could try would be to send a CTRL+ALT+DEL and then the Task Manager (and then hide it. Maybe you can do it all so fast the user would only see a quick flash). That usually aborts a shutdown when I've manually done it.
Second question on here...
Basically I am having a problem with a Stackoverflow exception that is thrown in my program, and I literally have no idea on how to locate the cause..
I have a program which has a plugin system, and it's a program that utilizes TCP in order to send and receive data; Server-> Client. I am making a remote console plugin, and the problem occurs when I do the command 'tree'; the filesystem entries listing command. For the first few seconds everything goes alright; the commands are being outputted (sent from Client to server). The receiving packets event isn't thread safe, so in the API I've provided an invocation function (to invoke methods on the UI thread). So therefore on output, it will do the following:
Public Sub ClientReadPacket(Sender As IClient, Pipename As String, Values As Object())
Select Case DirectCast(Values(1), ConsoleCommands)
Case ConsoleCommands.Output
ServerGUI.Send(Sub() ConsoleOutput.AppendText(Values(2) & Environment.NewLine))
End Select
End Sub
As you can see, the ServerGUI is an interface that I have provided for plugin development. And in the actual program - in the class that implements the GUI interface, I get a stackoverflow exception right here:
Private Sub ISend(del As System.Threading.SendOrPostCallback) Implements IGUI.Send
UIThread.Send(del, Nothing)
End Sub ' The break point is here; I assume that means that the exception ocurs in the line above.
The UIThread object is a synchronizationcontext of the main thread.
http://i.gyazo.com/870d9667f2272969b650cea836adca50.png
Update: So far I've narrowed it down to the following; it must be causing stackoverflow exception when calling SynchronizationContext.Send() too often, and the same happens when I rather use Invoke() in the plugin, it also gives a Stackoverflow exception.
I tried using asyncoperation, and this does not crash, but due to the fact that it's solely asynchronous is a problem, because my program becomes unresponsive when using Post(), because it continuously Posts (due to the fact that it will manage the next packet before the asyncoperation has posted.
OK guys, what's going on here?
In this VB code:
Module Module1
Sub Main()
If MsgBox("Restart?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
Application.Restart()
MsgBox("restarting")
Else
MsgBox("Cancel")
End If
End Sub
End Module
If this code is contained within a module, Application.Restart does not end the running application till the End Sub is hit. Any code that appears before then is executed - eg the 'Restarting' messagebox appears.
However, if the equivalent code is run within a form then Application.Restart terminates the running application immediately.
(Both cases correctly start a new instance). This behaviour does not appear to be documented anywhere - the implication in the docs is that it's synonymous with 'End' as far as the termination of the running instance is concerned. Am I missing something?
The best way to answer these questions it to look at the code itself using Reflector (or Microsoft's free for debugging code, when it is available).
With Reflector, you can see (in .NET Framework 4.0) System.Windows.Forms.Application.Restart looks for four different types of applications:
the initial check that Assembly.GetEntryAssembly is Nothing, throwing a NotSupportedException if it is;
the Process.GetCurrentProcess.MainModule.FileName is ieexec.exe in the same folder as the current .NET Framework (specifically the folder where the module defining Object is);
ApplicationDeployment.IsNetworkDeployed is True; and
the general case.
All three supported cases determine the method to start the process again, calls Application.ExitInternal and starts the process again.
Application.ExitInternal closes open forms, including the check for a form attempting to abort the close by setting FormClosingEventArgs.Cancel to True. If no form attempts to cancel, the forms are closed and, using ThreadContext.ExitApplication, all ThreadConnexts are cleaned up (Disposed or their ApplicationContext.ExitThread is called).
NB No Thread.Abort is called, so threads are NOT explicitly ended in any way. Also the Windows.Forms ModalApplicationContext, does not even call the ThreadExit "event" that a normal ApplicationContext does.
(Note that all three supported cases in Application.Restart ignore the result of Application.ExitInternal, so if a form does attempt to abort all that happens is any other forms don't get a chance to close, and the ThreadContexts are not cleaned up!)
Importantly for your question, it does NOT attempt to actually exit the current threads or the entire application (other than closing open forms and thread contexts).
However, by the time your MsgBox("restarting") executes the new application has been started.
You need to manually exit the application after calling Application.Restart. In the case of "run[ing] within a form" (you don't show the code where you tested this) either the form is closed and that is what you considered as the current application ending, or extra stuff that Windows.Forms (or VB) sets up means the application is exited by one of the "events" that throw when the clean up that does occur runs.
In other words, before testing it I expected the MsgBox to appear even when this code is in say the Click event of a form, with the form disappearing first, and the application restarting at the same time.
Having tested it, the MsgBox tries to appear, as I hear the beep that corresponds to it, and if I comment it out the beep does not occur. So something causes the application to exit even though it should have a message box open, and even putting a MsgBox in a Finally outside of the Application.Run does not appear on a Restart. (Note a similar effect is seen if you call MsgBox after Application.Exit.)
So something set up by Windows.Forms (or VB) does actually call something like Environment.Exit which calls the Win32Api ExitProcess and does not regard Finally or call Dispose or Finalize.
Note the Application.Restart documentation implies it is not for Console Applications though it currently works fine (except for the not quitting straight away, which is not implied by Application.Exit).
I am able to restart the application by closing and disposing all open forms, except the one that is calling.
For j As Integer = Application.OpenForms.Count - 1 To 0 Step -1
Dim frm = Application.OpenForms(j)
If frm.Text <> callingForm.Text Then
frm.Close()
frm.Dispose()
End If
Next
Application.Restart()
This is going to be, admittedly, a bit of a guess based on some fairly top-level reading I've done about Application.Restart(), but I think this is occurring due to the way Restart operates internally.
I think Restart() tries to do as much "intelligent" cleanup as it can for a process that is being terminated, and in what may be considered a fairly simplistic implementation, tracks certain of the things to be "cleaned up," possibly calling Dispose() on them (if applicable), which normally is a reasonable step to take. In your case, I'm going to make the guess that a background thread, or form, holds a reference to something - can't say what - that prevents the code from shutting down. It may become aware that it is executing inside a method, and wants to give that method a chance to complete before killing it - waiting on the completion of that sub/method.
I've seen other instances of Restart actually causing a really strange "Collection was Modified" error when no collection was involved. That's suggesting to me, probably naively, that the internal cleanup Restart is trying to achieve is reposed in a simple list, but in certain circumstances, the cleanup modifies the element in an unexpected way, a way that modifies the collection, causes the exception to be thrown, and aborts the exit/restart.
My company's main software package includes a hefty configuration library which loads on startup. This config library includes some mandatory settings which, if not supplied (via command line arguments), cause the entire application to exit.
This has never been an issue for our users, who launch the software via scripts which have the needed command line arguments supplied automatically. But sometimes when debugging our software we developers forget to specify the necessary arguments in Visual Studio's debug options; it's then very annoying to be greeted with the message Config specification invalid -- missing required parameters X, Y, and Z -- shutting down (I'm paraphrasing, of course).
It's not really a big deal, just an annoyance. Still, I felt it worthwhile to throw together a little form to make this process a little less painful; it notifies the user which parameters are missing and allows him/her to specify values for those parameters directly on the form, without having to restart the application.
My intentions were good (I think?), but it seems I can't get this solution to actually work. The problem is that after I've launched our software with missing settings, the form pops up and prompts me as expected; but after I've entered the required parameters and it's time for the application to "really" start, I get this InvalidOperationException:
SetCompatibleTextRenderingDefault must
be called before the first
IWin32Window object is created in the
application.
I think I understand what's going on here: the VB.NET project I'm working on is doing something like this "behind the scenes"*:
Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New MainForm)
End Sub
That call to SetCompatibleTextRenderingDefault is, apparently, throwing an exception because a form was already created and displayed prior to its execution.
Is there any way around this? Is there perhaps a more "proper" solution to this problem that I'm not thinking of (i.e., should I not be trying to collect user input via a form at all)?
*This is a best guess based on what I've seen in C# WinForms projects. Strangely, unless I'm missing something, it seems that VB.NET WinForms projects completely hide this from the developer.
Do make sure that you have the application framework option turned off and Sub Main selected as the starting method. Make it look similar to this:
Sub Main(ByVal args() As String)
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
If args.Length = 0 Then
Using dlg As New OptionsDialog
If dlg.ShowDialog <> DialogResult.OK Then Return
'' Use dlg result...
End Using
End If
Application.Run(New MainForm)
End Sub
Perhaps you could use the static Debugger.IsAttached (or even a #DEBUG directive) in your program's "main" function that feeds in some input file (say an XML file) into your parsed args collection instead?