Programs randomly getting System.AccessViolationException - c#

Okay so I have been having a lot of issues with debugging. I'm using VS2013 Pro and Windows 8.1. Both are up to date. The issue is, when I start debugging, half the time it throws this error:
An unhandled exception of type 'System.AccessViolationException'
occurred in System.Windows.Forms.dll
Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
Its not my code's fault either. I made a simple test as an example below. Note that I am not referencing System.Windows.Forms from this app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<int> testing = new List<int>();
for(int i =0; i < 50; i++)
{
testing.Add(i);
}
for (int i = 0; i < 50; i++)
{
Console.WriteLine(testing[i].ToString());
}
Console.ReadLine();
}
}
}
I have no idea what's causing this. It will work if I click okay and run it again, most the time. Occasionally I have to do it twice.
Any ideas?
Stack trace:

Changing the Platform Target to x86 works for me, It came to a point that stepping through the code was impossible without the forementioned Exception. I run Win 8.1 64-bit and Visual Studio 2013.

I also ran into this problem on windows10 using visual studio express2015. building to x86 did not fix my problem but the following workaround did the trick:
This issue is caused by the code which gathers return values. It is possible to work around the issue by disabling Managed return values.
Go to the System properties (Win8: WinKey+X, select ‘System’, Win7: Open ‘Properties’ from my computer)
Advanced System Settings
Environment Variables…
Click ‘New’ and add
Name: VSDebug_DisableManagedReturnValue
Value: 1
source: https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception

http://veriworld.verivox.ads/docs/DOC-6011?et=watches.email.document_comment#comment-4629
Seems that in some cases VS/.net framework has memory trampling issues. I really wish people would stop saying 'it cant be' when someone says something breaks.

There is nothing that looks like it may cause issues.
Did you try enabling breaking on exception? This will cause your code to pause when it encounter an exception.

I can confirm this problem. It occurs in a small (very trivial) WinForms program distributed with my own commercial app. It's never happened in any earlier version of VS going back to VS2005, including those run on the same machine. It only occurs in VS2013. My version of VS has no 3rd-party add-ins other than what's installed with VS itself. Problem occurs even when all code in "Main()" is commented out. I've tried rebooting, disabling virus checker, firewall, etc. Makes no difference which version of .NET my app targets either (2.0, 3.5, 4.0, whatever). It happens frequently but randomly. Sometimes it works, sometimes it doesn't. Go figure.

In my case, such VS behavior was caused by Comodo Firewall.
The solution is adding VS Projects folder to Comodo HIPS exclusions list (even if the HIPS is turned off!).
Here is a related thread Comodo forum: https://forums.comodo.com/empty-t98149.0.html

Related

Unable to run Console Application from Visual Studio: System.AccessViolationException

Description
When launching any Console Application, the code stops running immediately on an AccessViolationException (Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt). More info included in the next section.
Technical Symptoms
The Call Stack only contains external code:
Exception:Thrown: "The message filter indicated that the application is busy. >(Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))" (System.Runtime.InteropServices.COMException)
A System.Runtime.InteropServices.COMException was thrown: "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))"
Time: 12/10/2015 10:59:55 AM
Thread:vshost.NotifyLoad[15344]
I created a new Console Application, containing only Console.WriteLine("Hello world!");
Running the new Hello world app results in the same exception and an identical
call stack.
Background
I suspect this has nothing to do with the issue, as I will explain, but I feel it is important to answer the obvious question, "what were you doing when the issue happend?" The last change I made was adding an extension to my Selenium Driver to hotkey logout from an application:
public static void logout(this IWebDriver Driver)
{
Driver.FindElement(By.TagName("body")).Click();
new Actions(Driver)
.SendKeys(Keys.Control + Keys.Shift + "x")
.Perform();
}
I also made a change in my App.Config file for one of my projects, but reverting this had no impact either.
Removing this code (the Driver extension and/or the App.Config change) does not resolve this issue. Retrieving a previous check-in does not resolve the issue. I am the only person currently working on this solution.
Discoveries
As mentioned, this is happening for an empty Console Application. Windows Form Applications launch fine. Unit Test Projects launch fine as well.
Research
I've spent hours looking into this. It seems like every similar issue I have looked into is pertinent to debugging only or a .NET version. For me, the issue occurs with a Release as well. Additionally, I have been using .NET 4.5 without any issues or changes on that front. I can't find any articles that seem worth posting, but I might be overlooking something.
Visual Studio Info
Microsoft Visual Studio Ultimate 2013
Version 12.0.30501.00 Update 2
.NET Version 4.6.00081 (just noticed it says 4.5 in my project properties, though)
Running as Administrator
Feedback
When Running from devenv.exe /SafeMode, Visual Studio loaded with:
An exception was encountered while constructing the content of this frame. This information is also logged in "C:\Users\UserName\AppData\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml".
Exception details:
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at Microsoft.VisualStudio.Shell.Interop.IVsShell5.LoadPackageWithContext(Guid& packageGuid, Int32 reason, Guid& context)
at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.GetPackage()
at Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.ConstructContent()
Additionally, when trying to run, I get an error message of "Error while trying to run project: Invalid Pointer" (again, VS in devenv.exe /SafeMode - see how to run visual studio without plugin and all third party feature if unfamiliar)
Please let me know if I can provide any additional information.
It may be because when you name the project you can't put spaces, I put them and it gave me a AccessViolationException aswell, try using capitals to separate your words, but only use letters and no spaces to be sure.
I also faced this issue with Visual Studio 2010. More interestingly I had several projects in my solution (Console application, WPF application, Windows Forms application) but it was failing only when, I was setting the project which was of type "Console Application" as start up project. Following change finally helped me nail down the issue: Go to project properties of the console application project -> Go to "Debug" tab -> Go to "Enable Debuggers" section in right pane -> Check the "Enable unmanaged code debugging" check box as shown in the snapshot below. Root cause of why it happened is still not known to me. Only thing which I observed as fishy was that there were lot of windows updates which had got installed on my machine the previous night which mostly constituted of office updates and OS updates (More than a dozen KB articles).

Instance of AggregateException causes TargetInvocationException

I have a problem that an instance of an AggregateException causes a TargetInvocationException after a couple of accesses to an Icon resource.
I broke down the problem to the following steps to reproduce (.Net 4.0 full or client profile):
Create a new WinForms application (a console application will not work)
Add an arbitrary icon (.ico file) to the resources
Add the following code to the constructor:
new AggregateException();
for (var i = 0; ; ++i)
{
var icon = Resources.Certificate;
}
You have to change the resource name to the name of your resource.
That's all. Yes I know that this sample doesn't make sense. It's just to illustrate the problem. My working code is much more complex and all of this code is needed.
Without creating this excection the application will work forewer. But if this exception is created the access to the resource will fail with a TargetInvocationException. The InnerException told me that the operation has been finished successfully(?!?!) having a two-line stack trace in System.Drawing.Icon (ctor + Initialize).
What can I do to prevent this problem?
EDIT
It seems to be a problem using Windows 7. A binary which fails on Win 7 will run correctly in Win 8.1.
I found the reason for that problem:
The following system configuration is needed to reproduce the issue:
Windows 7 German Edition
Microsoft .Net Framework 4.5.2 installed (yes I know my binary is compiled against .Net 4.0)
KB2901983 installed
Having a machine which only contains the .Net Framework without KB2901983 the program works fine. After installing KB2901983 the program fails for the same binary (no recompilation required).
I tried to uninstall KB2901983 but it doesn't help. If it was once installed the program will fail. I tested it on a clean Windows 7 German Edition.

Exception while debugging Shims, UnitTestIsolationException

While using Shims, I get an exception while debugging. While others have reported this issue, none of the fixes that I have found have helped. This is the scenario. Although I discovered this on a full size project, I can reproduce it on a simple project. I only get this exception when using my work computer. If I try it on a coworkers computer or my home computer, I do not get the error.
Windows 7, fully patched.
VS Ultimate 2012, Update 4.
Default Processor Architecture of x64.
No Typemock or other mocking framework installed (that I am aware of).
No run settings or test settings in the solution (have verified in explorer).
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
}
}
If I run the test normally, no issue. However if I try to debug I get the exception on the using statement.
Exception:
Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationException was unhandled by user code
HResult=-2146233088
Message=UnitTestIsolation instrumentation failed to initialize. Please restart Visual Studio and rerun this test
Source=Microsoft.QualityTools.Testing.Fakes
StackTrace:
at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationRuntime.InitializeUnitTestIsolationInstrumentationProvider()
at Microsoft.QualityTools.Testing.Fakes.Shims.ShimRuntime.CreateContext()
at Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()
at MyLogTest.UnitTest1.TestMethod1() in c:\Users\XXXX\Documents\Visual Studio 2012\Projects\MyLogTest\MyLogTest\UnitTest1.cs:line 13
InnerException:
(** user id XXXX'd out for security **).
If I take that failing project from my work computer and put it on my home computer (also VS Ultimate 2012, update 4, Windows 7) I do not get the error while debugging.
I tried doing a full uninstall of VS (including renaming the old VS folder in Program Files) and a fresh install, I still get the exception.
In desperation I turned on logging for Visual Studio. The only significant difference that I noticed was the following in the log for devenv.TpTrace.log
Diagnostic: RockSteady initialized with the following extensions:
Diagnostic: Processing Queue .....
Diagnostic: Operation Dequeue : 'LoadPlaylistOperation'
Diagnostic: Operation left in the the queue: 1
Diagnostic: 'RunWithDebugFromContextOperation', hashcode:12788809
Diagnostic:
I tried looking for that "RockSteady" to see where it was coming from or what it is with no luck. These lines do not appear on my home computer when I perform the same test. I am thinking that there might be something installed on my machine from an SDK or something else that is causing an issue. I don't know that those lines above are the source of the problem, it is just the only major difference I am seeing.
I've been stuck on this for several days now. Any help is appreciated.

Visual C# Express 2010: Shift+F5 (Stop Debugging) causes Exception

Since yesterday I have a problem with Visual C# Express 2010. When I start my app in debug mode, I can't stop id from Visual. It causes Exception:
EventType : clr20r3 P1 : vcsexpress.exe P2 : 10.0.30319.1
P3 : 4ba1faa8
It starts to shutdown and after a while throws another error:
AppName: vcsexpress.exe AppVer: 10.0.30319.1 AppStamp:4ba1faa8
ModName: unknown ModVer: 0.0.0.0 ModStamp:00000000
fDebug: 0 Offset: 0ca09a88
I don't think its problem of my app, because I can push close btn on my app and it closes properly.
Do You have any ideas what could cause the problem and / or how to fix it?
This might be a crazy idea, but can you go back to the source of your project from the day before? It may not be your app, but it may in some odd way. Try debugging an earlier version of your app to see what happens.
If it runs ok, try to incrementally make the changes since that version to see whree it breaks.
I saw odd debug behavior years ago that ended up being related to some COM objects I was trying to use. Not suggesting you're using COM objects, but I too assumed it was VS's problem. It wasn't.
I was trying to solve the problem for quite some time. Then I left the project for a while and work on sth else. Recently I was reprogramming the project again and there were some problems again. I had no idea so one more time i reinstalled all dotNets and Visual Studio. What a surprise - problems are gone.I guess another mystery I can put into Microsofts X-File.
Thx for Your answers.

PerformanceCounters on .NET 4.0 & Windows 7

I have a program that works fine on VS2008 and Vista, but I'm trying it on Windows 7 and VS2010 / .NET Framework 4.0 and it's not working. Ultimately the problem is that System.Diagnostics.PerformanceCounterCategory.GetCategories() (and other PerformanceCounterCategory methods) is not working. I'm getting a System.InvalidOperationException with the message "Cannot load Counter Name data because an invalid index '' was read from the registry."
I can reproduce this with the very simple program shown below:
class Program
{
static void Main(string[] args)
{
foreach (var pc in System.Diagnostics.PerformanceCounterCategory.GetCategories())
{
Console.WriteLine(pc.CategoryName);
}
}
}
I did make sure I'm running the program as an admin. It doesn't matter if I run it with VS/Debugger attached or not. I don't have another machine with Windows 7 or VS2010 to test it on, so I'm not sure which is complicating things here (or both?). It is Windows 7 x64 and I've tried forcing the app to run in both x32 and x64 but get the same results.
It seems performance counters were corrupted on my system. Although I didn't follow this post exactly, it led me to the solution. Here is what I did:
In an command prompt with administrator/elevate privileges typed the following:
lodctr /?
Useful stuff in there...
Then typed:
lodctr /R
According to the docs from the prior step, this gets windows to rebuild the perf registry strings and info from scratch based on the current registry settings and backup INI files. I have a feeling this is what did the magic. However, next I noticed the .NET performance counters were not there anymore so based on this I typed the following to reload them:
lodctr "C:\Windows\Microsoft.NET\Framework64\v4.0.20506\corperfmonsymbols.ini"
Note that this path is for .NET Framework 4.0 on x64. You can imagine the path for other variations of the framework/platform. I'm guessing you should always load the counters from the highest version of the .NET framework that you have installed, but that is just a guess.
I hope this helps someone else someday!

Categories