Cannot access a disposed object 'RichTextBox' - c#

A program I developed in Microsoft Visual Studios 2010 using c# has been generating the following error: https://dl.dropboxusercontent.com/u/19853155/code%20error%2001.jpg
I have kind of isolated the issue down to this segment of code:
if (gui.rawLogLSM.InvokeRequired)
{
gui.rawLogLSM.Invoke(new MethodInvoker(delegate
{
gui.rawLogLSM.AppendText(t.ToString());
gui.rawLogLSM.ScrollToCaret();
}));
}
else
{
gui.rawLogLSM.AppendText(t.ToString());
gui.rawLogLSM.ScrollToCaret();
}
Basically in this segment of code, I am reading raw data from a serial port, and printing it into a text box, byte by byte. (I can't read the whole buffer in at a time, as that invalidates what we're doing for the project).
I am not wholly sure how this error is actually generated or under what conditions. The error has only presented itself when a co-worker is using the application in my absence, and I've been unable to recreate the error.
The error from info from the exception comes up in form of a message box due to me having a try/catch around a larger block of code, within which the above code is apart of.
So my question is mostly, how can I solve this error or what should I be doing to force said error to show itself?
Thanks for the help!

Could it be that the invoke is on a different thread and the exception is thrown when trying to invoke the textbox while another thread has disposed the textbox(on form close maybe?)? If this is because the textbox is disposed on different thread, one solution would be to surround AppendText and ScrollToCaret inside the invoke with try/catch and swallow that specific error.

The error itself is pretty straightforward: your rich text box is being disposed before you access it. Unfortunately, these can be very nasty to track down, especially if you can't reproduce it.
Do a sanity check and make sure that the RTB is indeed created before the Append()'ing code is called, but my gut tells me you'd get constant errors if it wasn't.
To me, the first step is to reliably reproduce it. Use your coworker's machine, have them demonstrate what they were doing when the error popped up, ensure the framework and application versions are the same, etc etc.
Once you can reproduce it, you'll have to find WHERE the object is disposed. You can do it manually by right-clicking a call to the dispose and choosing "show all references". Set breakpoints on each of them, or use some other monitoring scheme (like a log, which can be used to watch programs on non-development machines). Remember that the System.Diagnostics.StackTrace class is useful for seeing what called Dispose.
There are also tools that monitor memory usage and disposal that can help you out.
I'd also recommend turning debug mode on and giving your coworker the debug-enabled executable and the symbol file (pdb) as this may help track the problem.
Other things to check are race conditions, simultaneous/cross-thread access, exceptions in other threads that may be swallowed by the CLR, only to fudge up your code later on, and make sure you end all threads before you close your form. If you don't, weird stuff can happen. At best, your program will continue to hang in memory, invisible to all but task manager. Worse, you can pop up random error dialogs "out of the blue" as something finally fails. In your case, it might be failing immediately.

Related

Visual Studio "An unhandled win32 expcetion occured" when clicking button often

I have a strange issue with my C# UWP-Win10 app. When I re-size the window often or clicking a random button often (>3 times), I'm getting the error:
An unhandled win32 exception occurred in bla.exe [bla-id]
After closing this window the app crashes and in the output-window I get:
The program '[bla-id] bla.exe' has exited with code -1073741811 (0xc000000d).
No more information from Visual Studio. I'm using the serial-port in this app and I've noticed that this error occurs only when I'm connected to the device. But: I've added an empty button (without a Click-handler) and the same error occurs on this button.
Additionally I've looked in the eventviewer and saw the crashed-module:
ntdll.dll (offset 0x00000000000f5670)
How can I trace down the issue? I'm not using external APIs or something else.
After a while (two weeks) of testing and debugging I've found the issue: The garbage collector is closing the serialport inputstream and thus the DataReader (which is reading the serialport) dies instantly and throws this unspecified exception. Basically this was an issue with the datareaader not disposing correctly in code. "Mystery" solved.
I know this post is three years old, but I found it when I was searching for a solution to this exact same problem, and maybe my experience can help the next person who stumbles upon it.
After reading the OP's response to his own question, I started investigating garbage collection, object disposal, and etc. I found that if my DataReader and DataWriter objects were global in scope, then they were at risk of being garbage collected mid-use. What worked for me was to locally scope those objects every time I needed them, with a using(DataWriter dw = new DataWriter(EventHandlerForDevice.Current.Device.OutputStream)) { ... } block, or similar for the DataReader object. Since implementing them like this, I haven't had any of the win32 exceptions whatsoever. Hope this helps!

0x80131623 Error on Tab Change, WebBrowser Issue?

I'm having an issue with WPF's WebBrowser control. It's crashing with the titular error when I'm changing tabs - I think I know why (explained below), but I can't think of a way around it. I'm looking for either ideas on how I might reorganize the code to work correctly, or alternatives on what I'm using to achieve my goal.
The setup of the program is this: There are multiple tabs, containing Borders/Grids/etc. On one of these tabs, there is a Grid which has "Widgets", each containing a WebBrowser. These browsers are loading various locally-hosted pages with information for the user. To make the widgets look good, some code runs in the LoadCompleted event of the browser.
brow = new WebBrowser();
brow.LoadCompleted += wb_LoadCompleted;
(The wb_LoadCompleted function isn't important: the program will crash as it's being called, not during its execution.)
Also, when the user changes tabs, these Widgets have a Dispose function that's called.
brow.LoadCompleted -= wb_LoadCompleted;
brow.Source = null;
Now if the user opens the tab with these Widgets, then after the pages begin loading, but before they finish loading and call that event, the user switches tabs again, the program will crash once it attempts to call the wb_LoadCompleted event. I think this is happening because of the error described here. The handlers have been disposed because the tab changed, but the thread wants to call the handlers. In Visual Studio, if I place a break on the wb_LoadCompleted method, it'll be on that breakpoint when the error is thrown, so I think the program still knows what code it should be running, it just doesn't have permission to.
So far I've been unable to find a workaround or solution. Beyond code fix attempts, I've tried using different browser controls (Awesemonium, and a few others); while they work without this error, but they also balloon the size of our program distribution by 30 meg. That nearly doubles the size, and it's not feasible for us to do so. Any alternative browser control that works would be great, but it needs to be ~10 meg max.
I can also share some other code if you let me know what you need to see; however, I'd imagine this is more of a timing/placement/ordering issue than current code issue, if that makes sense.
e; Adding the full error text:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in -programpath-
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x6bd5e4ad, on thread 0xa54. The error code is 0x80131623. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

InvalidOperationException (sometimes) when getting keyboard state

I am trying to get the keyboard state in my XNA application with the following code:
this.OldKeyboard = this.NewKeyboard;
this.NewKeyboard = Keyboard.GetState();
this.OldMouse = this.NewMouse;
this.NewMouse = Mouse.GetState();
However, sometimes (I think about 60%) when I start my game, I get an InvalidOperationException with the following message:
An invalid operation occurred when trying to query the keyboard state.
The result code was 126.
at Microsoft.Xna.Framework.Input.Keyboard.GetState(PlayerIndex playerIndex)
at Microsoft.Xna.Framework.Input.Keyboard.GetState()
at GameLib.GameBase.Update(GameTime gameTime) in MY_PATH\GameLib\GameLib\GameBase.cs:Line 58.
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at ...
My searches on google and SO did not give me any results on this code.
What could be the cause for this and why doesn't it occur everytime or never, but only sometimes when starting the project?
Edit: My thread layout:
Main thread
starts Game.Run
starts a network initializer in a separate project (in Initialize)
which starts a new thread for network I/O
When creating a new project only containing Keyboard.GetState(), I apparently get an error code of 0, which translates to
ERROR_SUCCESS
0 (0x0)
The operation completed successfully.
See my screenshot below, I do not know why a success would trigger an InvalidOperationException.
Keboard.GetState uses the win32 function GetKeyboardState (MSDN) internally. If that fails, it gives an error code from this list, which XNA fetches and packs into that exception for you.
That error code translates to: "The specified module could not be found."
Where "module" basically means DLL. And "not found" might refer to the DLL being loaded, or a DLL that it, in turn, requires (and so on). It's an extremely unhelpful error message.
I'm not really sure what DLL GetKeyboardState might be trying to load, or why it might fail intermittently.
Probably the first step to try and fix this would be to create a new, blank project and see if you get the same result, so you can figure out if it's your code, or something wrong with your system or XNA install.
(I imagine actually debugging this properly might involve using Process Monitor to catch what DLL it is failing to load.)
Also, Blau is correct - all input in XNA must be done on the main thread.
I don't know how old this thread is, but I heard it has something to do with your firewall. The same error happened to me when I updated my antivirus (do you happen to use Comodo?) Anyway, check that out, and see if it helps. It has nothing to do with XNA, I tested in visual c# express, visual studio 2012, and 2013, with same results, then I tried with a fresh project that only called the keyboard state, and it happened again. And none of that happened before I updated the antivirus...

Errors in Razor pages cause server to hang

I've been writing an app using the awesome new Razor view engine and for the most part, things have been great.
One issue I keep running into, however, is that if I should happen to write invalid code, such as referencing a null property or even a non existent property, rather than throwing an error, something happens in the background that causes the browser to wait and wait and wait and if I do not cancel the browser's request quick enough, IIS will simply hang.
It seems as if it enters some sort of loop. CPU usage goes up (though not terribly high) and restarting IIS via either GUI or iisreset command seems to take abnormally long (presumably while it waits for the process to safely shutdown).
This also happens for other invalid code scenarios such as failing to close a code block with a closing brace.
I notice this behavior on more than one machine.
Any ideas if this is a known issue or have I mis configured something?
Thanks!
I found the problem. I had installed a package via NuGet called "Razor Debugger" and apparently this plugin was intercepting Razor errors somehow, and was consequently not showing them.
Removing that package now allows Razor to work properly. What a relief.
Steer clear of this library.

Does playing a Program from VS2005 cause a program to work any different than the .exe file?

There is a program where I work that works fine when running the .exe file but works differently from expected when opened in VS2005 and played from there. I am therefore asking on here if anyone knows of anything that would work in the .exe file but not the debug from VS? I am not able to post the code for the buttons I'm talking about but I'll try to explain the best I can.
There is a receiver hooked up to the computer. When the button is pressed on the program, it shows a message and waits for a signal to be received. After the signal is heard the first message box is supposed to close and another is supposed to open. When using the .exe file this happens just fine. However when playing from the program from VS2005 (the same one from which the .exe was made) the second message doesn't come up when it is supposed to and when I can make it come up, the first box doesn't close. There is also a timer involved if that helps.
Also, is there a fundamental difference between how the two operate when executing the program?
If I need to make anything more clear or give more details please let me know.
Running a program under the supervision of a debugger can change the timing of events compared to running the program standalone. The debugger slows things down. Normally, this doesn't make any difference to the operation of the program, but if you have code that is dependent on the "coincidental" rapid timing of some activity, that happy coincidence may be broken when things slow down under debugger control.
The debugger can also cause changes in focus and activation depending on where you set your breakpoints - generally not a good idea to set a breakpoint in focus change or activation events because stopping at the breakpoint will change focus to the debugger, away from your app. But these are interaction issues. Just running your program under the debugger with no breakpoints shouldn't affect focus or activation in your app.
Review your code carefully. Consider what could happen to your program flow if you inserted delays between every source code statement. If that could lead to problems, you have a design bug that needs to be fixed. Reliance on coincidental timings will lead to bug reports and support calls, particularly if your customers have slower hardware than your development machine.
When you run under the debugger, or even in the VS testing host, there are some subtle differences. This shouldn't effect your program under normal circumstances, however, since most of the differences are similar to running (the debug version) of your application on a slower system.
Given your descriptions, I suspect that your problem is actually due to calling to the UI from a different thread than the control was constructed with. Make sure to always marshal any calls to the UI using Control.Invoke or Control.BeginInvoke.
It may be an issue with the Host Process, disabling it is a painless click and just as easy to re-enable. It may be worth giving a try.
Disable Host Process
I know this can effect Direct X and other API but I've never had exactly the situation you are in so I make no promise.

Categories

Resources