Stackoverflowexception - Unable to find out the cause - vb.net

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.

Related

How do I find out what called my shared function

I have a function in vb.net that is shared. At one point it throws an error that says an 'open datareader already exists'. But this function is called from several different places in the program. How can I find out which part of the program called the function when it errors out?
You go to the Debug menu, show the Exceptions window, put a tick next to CLR exceptions and then run your program until it errors. As soon as the exception is raised VS will break, you will be able to see the call stack, and find out where the code was before. Note that this causes VS to stop on every exception, handled or not; it can become tedious to get to where you want to be - untick the "always break when this type of exception is thrown" in the exception helper if you just keep getting irrelevant exceptions breaking before this error you're trying to chase
It sounds like you're perhaps not creating/disposing of your DB access resources properly, especially if this is a static/shared context. Are you trying to reuse one DB connection? It wouldn't hurt to post the code of the faulting module

Need to call functions and subs from windows services in VB.Net

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.

How to correctly terminate an application?

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

Application.restart - Puzzling behaviour in VB.Net

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.

.Net Asynchronous Delegate Abortion

Background: My application is used to execute tests using Selenium RC servers, and occasionally I'm running into a problem when my call to a Selenium command doesn't return the response from the RC server - it then ends up blocking the thread that is executing the test.
Sample Code:
Private Delegate Function DoCommand_Delegate(ByVal command As String, ByVal args() As String) As String
...
asyncCommand = New DoCommand_Delegate(AddressOf server.DoCommand)
asyncResult = asyncCommand.BeginInvoke(command, args, Nothing, Nothing)
Try
... (I have it use the AsyncWaitHandle to wait for periods of 10 seconds up to two minutes. At the end of each period it runs some checks for common problems that block Selenium from returning a response (modal dialogs) - I don't think that part is relevant to this question, it's just necessary.)
Finally
result = asyncCommand.EndInvoke(asyncResult)
...
At the time EndInvoke is called, the worker delegate has either already finished or needs to be aborted. Most of the time it already has a response so it works just fine, but on rare occasion Selenium RC's DoCommand doesn't return, so the thread sits there locked.
Finally, my question: is there a resource-friendly way to abort the executing delegate, or do I need to convert it to use a manually controlled thread that can be aborted and disposed?
Note: This is not a question regarding Selenium, just proper multithreading.
Note 2: I've considered doing the following in the Finally before calling EndInvoke:
If Not asyncResult.IsCompleted Then asyncResult.AsyncWaitHandle.Close()
... But I don't know if that would actually work correctly, or what damage that could cause.
There is no way to do the following at the same time:
Abort/kill a thread non-cooperatively
Without destroying all state associated with it (AppDomain/process)
Implies: Either terminate cooperatively (not possible here) or kill the process (AppDomain not enough because native state is involved) or don't kill the thread.
You could just not kill the thread and leave it there hanging. The rest of your program (the remaining tests) can continue to execute.
I'd not be happy to see this in production but for a test suite this could be ok (assuming the hang cannot be fixed).
Why can't a thread be aborted? This has been covered a number of times on Stack Overflow already.