How can I get LabView to stop locking my .NET DLL? - c#

I'm trying out LabView, experimenting with how to use it in conjunction with .NET. I've managed to create a small app that reads a gauge, converts the value in .NET, and displays the result on another gauge.
The trouble is that when I try to add to the .NET project and rebuild, the DLL is locked and I can't overwrite it. NI claims that LabView uses Shadow Copying. But if that's true, my DLL shouldn't be locked.
Is there some way I can get LabView to stop locking the DLL? Other than exiting LabView every time I want to rebuild, which seems like a tedious fix.

What I believe is happening in your application is the following:
When Labview launches, it pulls in the dll of your application, tightly locking it into memory. As such, the file is locked and Visual Studio won't be able to overwrite this file (I have directly seen this behavior in other applications). Since the dll never gets freed until Labview exits, you need to find a way to "trick" Labview into loading a fresh dll every time you re-compile.
Here is what I recommend:
In LabView, instead of loading your dll directly, as suggested by Chris Sterling you'll want to create a "wrapper" dll that will load your specific LabView dll through an interface
By utilizing an interface stored in your wrapper dll you fully decouple the two dlls, which will prevent the wrapper dll from knowing about/locking your primary dll. Later, when you are finished with the debugging, you can directly link the dll to LabView.
Here is roughly how the code should look:
public class LabViewWrapper : IYourCustomClass
{
private IYourCustomClass _labViewClass;
private string labviewPath = "Full Path to labview dll";
public LabViewWrapper()
{
Assembly assembly;
try
{
using (FileStream fs = File.OpenRead(labviewPath))
{
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int read = 0;
while ((read = fs.Read(buffer, 0, 1024)) > 0)
ms.Write(buffer, 0, read);
assembly = Assembly.Load(ms.ToArray());
ms.Close();
}
fs.Close();
}
Type t = assembly.GetType(IYourCustomClass);
_labViewClass= (IYourCustomClass)Activator.CreateInstance(t);
}
catch
{
// Unable to load dll dynamically
}
}
// Implement all the methods in your interface with something like the following:
/// <summary>
/// Your Custom Method
/// </summary>
public void CustomLabViewMethod()
{
_labViewClass.CustomLabViewMethod();
}
}
By doing it this way, you are loading the dll from memory, and therefore labview never locks your original dll that you compiled. The only real downside with this is that it does make debugging harder, if you want to insert breakpoints, you'll likely need to directly reference the source dll.
Note: One thing I am not sure about, but I believe will "work out" is whether Labview is smart enough to re-construct the object every time it executes your code, or whether it just keeps the same object throughout the session. If it does end up doing the later, you'll need to add code to "reload" the dll from the file system every time you launch your custom widget.

You could create a light DLL wrapper that itself has explicit runtime loading and unloading of your main DLL. That way the wrapper stays locked, but you can update your frequently changing code DLL quickly.

I'm doing a test in LV2012 with a C# class with a new custom class in a separate folder from the Labview VI. I'm able to recompile the C# code in VS2010 without having to close out Labview, but Labview doesn't see the changes to the DLL (if any are made). For Labview to see the changes in my test case, it needs to be fully closed and reopened.
For Labview C++ DLLs, you for sure have to close down the calling VIs, as the reference to the DLL is left open. You only need to close down to the Labview Start-up pane though.
You can have VS automatically spawn Labview.exe in a C# project by going to Project->Properties->Debug->Start External Program. When you hit F5 in VS, the DLL compiles and spawns Labview. However, VS doesn't automatically attach the DLL to process, which is really, really obnoxious. Dunno if that helps or not.
Personally, I like the way C# methods integrate with Labview, but find C++ more powerful. Working with C++, you can also spawn Labview in a similar way as above, but it automatically attaches the DLL to the Labview.exe process, making debugging a one step process of just hitting F5. You can still use classes and such in C++, you just have to wrap C functions to call them in Labview. Given the one step debugging and power of C++, I find it superior to C# when using external code in Labview.

The terminology there is a little unclear, because it's talking about LV "calling" an assembly, and I don't know if that refers to accessing the assembly at edit time or actually calling it at run-time. If it's the second, that would probably explain why it's locked.
I'm not a .NET programmer, so I have no idea what the actual solution is, but I'm guessing that you don't actually need to fully close LV to release the lock. It's possible that closing the project is enough, although I know that's not necessarily any better and it probably won't help if the lock happens at the process level.

get http://www.emptyloop.com/unlocker/
unlocker -h for its comand line options
run in prebuild. with unlock command on relevante dlls.
if only unlock doesn't help use unlock+delete.
simple as
Unlocker mydllpath.dll /s /d

You'll find that this behavior changes depending on how the dll is distributed.
If Labview is calling the assembly by a static location on disc (specified by a path input), you'll find that you cannot rebuild the dll while the Labview application is open.
However, if the dll is registered and Labview accesses it by name, you can rebuild and reinstall to your heart's content, and Labview will update its reference to the DLL once it is closed and reopened.
I accidentally stumbled across this when sharing a .Net assembly through COM Interop, as well as installing it to the GAC.
There used to be KnowledgeBase articles on this topic as recently as 2017, but they appear to be missing now.
I've included the official Labview help guide on loading assemblies here.

Related

How to update dll-file without main program being restart?

How to update dll-file without program being restart?
I want to create my "Updater" class. It's main idea is to
check local(connected to executive file) and server dll-files,
and when newer version is available, copying server file to local.
Code:
Updater updater = new Updater(LOCAL_PATH, SERVER_PATH);
if (updater.IsAvailableNewerVersion)
updater.Update();
Updater's ctor take two paths - to server dll and to local dll and calculate their Versions.
Then I call a property IsAvailableNewerVersion - if it's true (available version is newer then a local), I call Update method.
Main Idea of Update method is to copying server dll-file to local with overwrite, and say to user to restart program.
Code:
public class Updater
{
private readonly string _localPath;
private readonly string _serverPath;
private readonly Version _currentVersion;
private readonly Version _availableVersion;
public Updater(string localPath, string serverPath)
{
_localPath = localPath;
_serverPath = serverPath;
_currentVersion = AssemblyName.GetAssemblyName(_localPath).Version;
_availableVersion = AssemblyName.GetAssemblyName(_serverPath).Version;
}
public bool IsAvailableNewerVersion => _availableVersion.Major > _currentVersion.Major ||
_availableVersion.MajorRevision > _currentVersion.MajorRevision ||
_availableVersion.Minor > _currentVersion.Minor ||
_availableVersion.MinorRevision > _currentVersion.MinorRevision ||
_availableVersion.Build > _currentVersion.Build ||
_availableVersion.Revision > _currentVersion.Revision;
public void Update()
{
try
{
File.Copy(_serverPath, _localPath, true);
}
catch (Exception e)
{
MessageBox.Show("Unable to copying file - " + e);
return;
}
MessageBox.Show("File was successfully updated. Please restart program.");
}
}
Is there a way to check dll-files before they being used?
How to update dll-file without program being restart?
P.S.
I think to use server dll-files, but my program becomes dependent on the server that is not good.
You can't really unload / change the assemblies in a running app-domain; so basically you have two options here:
use a launcher exe that does this work and invokes an inner exe to do the real work, shutting it down when complete (launching a new one either before or after the shutdown)
use multiple app-domains in a single exe, isolating where each loads from
The second approach is more useful for server applications, since you can handle the network IO in the outer exe and funnel requests through to the inner app-domain, just changing a single reference to swap between the two systems. However, app-domains aren't in .NET Core, so you should be aware that it limits your flexibility.
1. Is there a way to check dll-files before they being used?
If you are using a single EXE, it depends on how you use the DLLs. If they are hard coupled to your app, I do not know any way on how to do so.
But if the DLLs are just implemeting interfaces of your core DLLs, you could load them using:
Assembly assembly = Assembly.LoadFrom("path\orbital.dll"));
Type type = assembly.GetType("FullClassName");
object instanceOfMyType = Activator.CreateInstance(type);
This requires you to follow some design patterns, what would be good for your app. But if you already have several DLLs strongly coupled (that means, you added them as reference in your Visual Studio project and are creating objects as var object = new YourOtherDLLNamespace.YorObjectInTheOtherDLL()) then you will probably take a lot of time to change to this approach.
The good about this approach is that you could check the DLL version before loading it, copy a new version from a server (or any other method you find appropriate) and then load it.
2. How to update dll-file without program being restart?
Ok, lets suppose you made just like my suggestion on item 1. Once you loaded the DLL, you wont be able to Unload it. You could destroy all the objects using the garbage collector, but that won't change the way windows is loading it.
So the basic answer for a single EXE is no.
Other solutions
You could wrap your solution in other EXE that keeps constantly checking if the DLL is updated, send a custom event (so that your app EXE would now what is going on an take appropriate action before shutting it down), notify the user and, if the user wants to do so, then you could close the app. Then your other app wrapper would update it and launch the EXE again.

Why in C# Console applications from template is crashes? [duplicate]

I'm hoping someone can enlighten me as to what could possibly be causing this error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I cannot really post code because this error seems to get thrown in any random area of the application. The application will run anywhere from 12-48 hours before throwing the error. Sometimes it will stop in a seemingly random spot and throw the above error, other times the entire application stops and I get a screen with an error that says something along the lines of "There was a fatal error in... This may be a bug in the CLR or..." something about PInvoke or other non relevant info. When this happens all threads show terminated and there is no debugging information available.
In a nutshell this is what the application does:
Its a multi-threaded server application written in entirely in C#. Clients connect to the server via socket. The server runs a virtual "environment" for the clients where they can interact with each other and the environment. It consumes quite a bit of memory but I do not see it leaking. It typically consumes about 1.5GB. I dont think its leaking because the memory usage stays relatively constant the entire time the application is running. Its constantly running code to maintain the environment even if the clients are not doing anything. It uses no 3rd party software or other APIs. The only outside resources this application uses is socket connections and SQL database connections. Its running on a 64bit server. I have tried debugging this in VS2008 & VS2010 using .net 2.0, 3.5, and 4.0 and on multiple servers and the problem still eventually occurs.
I've tried turning off compiler optimizations and several microsoft hot-fixes. Nothing seems to make this issue go away. It would be appreciated if anyone knows any possible causes, or some kind of way to identify whats causing the problem.
I have just faced this issue in VS 2013 .NET 4.5 with a MapInfo DLL. Turns out, the problem was that I changed the Platform for Build from x86 to Any CPU and that was enough to trigger this error. Changing it back to x86 did the trick. Might help someone.
I faced this issue with Visual Studio (VS) 2010. More interestingly, I had several types of projects in my solution namely a console application project, a WPF application project, a Windows Forms application project, etc. But it was failing only when, I was setting the Console Application type of project as start-up project of the solution. All the projects were completely empty. They had no user code or any 3rd party assemblies added as reference. All projects are referencing only the default assemblies of .NET base class library (BCL) which come with the project template itself.
How to solve the issue?
Go to project properties of the console application project (Alternately you can select the project file in solution explorer and press Alt + Enter key combination) > Go to Debug tab > Check the Enable unmanaged code debugging check box under Enable Debuggers section (refer screenshot) > Click Floppy button in the toolbar to save project properties.
Root cause of the issue is not known to me. Only thing I observed was that there were lot of windows updates which had got installed on my machine the previous night. All the updates constituted mostly of office updates and OS updates (More than a dozen KB articles).
Update: VS 2017 onward the setting name has changed to Enable native code debugging. It is available under Debugger engines section (refer screenshot):
The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved.
Finally tracked this down with the help of WinDBG and SOS. Access violation was being thrown by some unknown DLL. Turns out a piece of software called "Nvidia Network Manager" was causing the problems. I'd read countless times how this issue can be caused by firewalls or antivirus, neither of which I am using so I dismissed this idea. Also, I was under the assumption that it was not environmental because it occurs on more than 1 server using different hardware. Turns out all the machines I tested this on were running "NVidia Network Manager". I believe it installs with the rest of the motherboard drivers.
Hopefully this helps someone as this issue was plaguing my application for a very long time.
Try to run this command
netsh winsock reset
Source: https://stackoverflow.com/a/20492181/1057791
This error should not happen in the managed code. This might solve the issue:
Go to Visual Studio Debugger to bypass this exception:
Tools menu -> Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"
Hope it will help.
I got this error when using pinvoke on a method that takes a reference to a StringBuilder. I had used the default constructor which apparently only allocates 16 bytes. Windows tried to put more than 16 bytes in the buffer and caused a buffer overrun.
Instead of
StringBuilder windowText = new StringBuilder(); // Probable overflow of default capacity (16)
Use a larger capacity:
StringBuilder windowText = new StringBuilder(3000);
I've ran into, and found a resolution to this exception today. It was occurring when I was trying to debug a unit test (NUnit) that called a virtual method on an abstract class.
The issue appears to be with the .NET 4.5.1 install.
I have downloaded .NET 4.5.2 and installed (my projects still reference .NET 4.5.1) and the issue is resolved.
Source of solution:
https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception
It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.
What OS and service pack are you running?
I had this problem recently when I changed the development server for a project. I was getting this error on the line of code where I declared a new OracleConnection variable.
After trying many things, including installing hotfixes, I tried changing the references Oracle.DataAccess and System.Data.OracleClient in the project and it worked!
When a project is moved to a new machine, I suggest you renew all the references added in that project.
Did you try turning off DEP (Data Execution Prevention) for your application ?
Verifiable code should not be able to corrupt memory, so there's something unsafe going on. Are you using any unsafe code anywhere, such as in buffer processing? Also, the stuff about PInvoke may not be irrelevant, as PInvoke involves a transition to unmanaged code and associated marshaling.
My best recommendation is to attach to a crashed instance and use WinDBG and SOS to dig deeper into what's happening at the time of the crash. This is not for the faint of heart, but at this point you may need to break out more powerful tools to determine what, exactly, is going wrong.
I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)
Ok, this could be pretty useless and simply anecdotal, but...
This exception was thrown consistently by some Twain32 libraries we were using in my project, but would only happen in my machine.
I tried lots of suggested solutions all over the internet, to no avail... Until I unplugged my cellphone (it was connected through the USB).
And it worked.
Turns out the Twain32 libraries were trying to list my phone as a Twain compatible device, and something it did in that process caused that exception.
Go figure...
in my case the file was open and therefore locked.
I was getting it when trying to load an Excel file using LinqToExcel that was also opened in Excel.
this is all I deeded
var maps = from f in book.Worksheet<NavMapping>()
select f;
try {
foreach (var m in maps)
if (!string.IsNullOrEmpty(m.SSS_ID) && _mappings.ContainsKey(m.SSS_ID))
_mappings.Add(m.SSS_ID, m.CDS_ID);
} catch (AccessViolationException ex) {
_logger.Error("mapping file error. most likely this file is locked or open. " + ex);
}
I got the same error in a project I was working with in VB.NET. Checking the "Enable application framework" on the properties page solved it for me.
I had the same error message:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
In my case, the error went away after clean and re-build the solution.
Make sure you are not creating multiple time converter objects.
you can use to singleton class to create a converter object to resolve the below error with Haukcode.WkHtmlToPdfDotNet library
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
This issue is almost invariably a simple one. The code is bad. It's rarely the tools, just from a statistical analysis. Untold millions of people are using Visual Studio every day and maybe a few are using your code - which bit of code is getting the better testing? I guarantee that, if this were a problem with VS, we would probably already have found it.
What the statement means is that, when you try to access memory that isn't yours, it's usually because you're doing it with a corrupted pointer, that came from somewhere else. That's why it's stating the indication.
With memory corruption, the catching of the error is rarely near the root cause of the error. And the effects are exactly what you describe, seemingly random. You'll just have to look at the usual culprits, things like:
uninitialised pointers or other values.
writing more to a buffer than its size.
resources shared by threads that aren't protected by mutexes.
Working backwards from a problem like this to find the root cause is incredibly difficult given that so much could have happened between the creation of the problem and the detection of the problem.
I mostly find it's easier to have a look at what is corrupt (say, a specific pointer) and then do manual static analysis of the code to see what could have corrupted it, checking for the usual culprits as shown above. However, even this won't catch long chains of problems.
I'm not familiar enough with VS to know but you may also want to look into the possibility of using a memory tracking tool (like valgrind for Linux) to see if it can spot any obvious issues.
My answer very much depends on your scenario but we had an issue trying to upgrade a .NET application for a client which was > 10 years old so they could make it work on Windows 8.1. #alhazen's answer was kind of in the correct ballpark for me. The application was relying on a third-party DLL the client didn't want to pay to update (Pegasus/Accusoft ImagXpress). We re-targeted the application for .NET 4.5 but each time the following line executed we received the AccessViolationException was unhandled message:
UnlockPICImagXpress.PS_Unlock (1908228217,373714400,1341834561,28447);
To fix it, we had to add the following post-build event to the project:
call "$(DevEnvDir)..\tools\vsvars32.bat"
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\amd64\editbin.exe" /NXCOMPAT:NO "$(TargetPath)"
This explicitly specifies the executable as incompatible with Data Execution Prevention. For more details see here.
i had this problem too .
i was running different solutions at the same time using visual studio , when closing other solutions and running just the target solution , it worked fine without that error .
Got this error randomly in VS1017, when trying to build a project that was building perfectly fine the day before. Restarting the PC fixed the issue worked (I also ran the following command beforehand, not sure if it's required: netsh winsock reset)
In my case I had to reference a C/C++ library using P/Invoke, but I had to ensure that the memory was allocated for the output array first using fixed:
[DllImport("my_c_func_lib.dll", CharSet = CharSet.Ansi)]
public static extern unsafe int my_c_func(double input1, double input2, double pinput3, double *outData);
public unsafe double[] GetMyUnmanagedCodeValue(double input1, double input2, double input3)
{
double[] outData = new double[24];
fixed (double* returnValue = outData)
{
my_c_func(input1, input2, pinput3, returnValue);
}
return outData;
}
For details please see: https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/
In some cases, this might happen when:
obj = new obj();
...
obj.Dispose(); // <----------------- Incorrect disposal causes it
obj.abc...
This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.
[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
Running Visual Studio "as Administrator" solved the problem for me.
In my case the FTDI utility FT Prog was throwing the error as it scanned for USB devices. Unplugging my Bluetooth headphones from the PC fixed the issue.
I got this error message on lambda expression that was using Linq to filter a collection of objects. When I inspected the collection I noticed that its members weren't populated - in the Locals window, expanding them just showed "...". Ultimately the problem was in the repository method that initially populated the collection - Dapper was trying to automatically map a property of a nested object. I fixed the Dapper query to handle the multi-mapping and that fixed the memory error.
This may not be the best answer for the above question, but the problem of mine was invalid dispose syntax and usage of lock(this) for a buffer object. It turned out the object was getting disposed from another thread because of "using" syntax. And the processing lock() was on a loose type.
// wrong lock syntax
lock(this) {
// modify buffer object
}
I changed the locks to
private static readonly object _lockObject = new object();
lock(_lockObject) {
// modify buffer object
}
And used suggested C# disposing syntax and the problem gone.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any managed objects here
buffer?.Free();
}
disposed = true;
}
I've experienced the same issue when running a .Net Framework Web API application locally under IIS.
The issue was that I had previously updated the IIS App Pool's Managed Pipeline Mode to 'Classic'. Setting it back to 'Integrated' fixed the issue for me.
For Xamarin Forms one can wrap the code in
Device.BeginInvokeOnMainThread(() =>
{
//your code
});
Happened for me in UWP when updating UI from the wrong thread.

Using filehelpers ExcelStorage - Excel File not opening

I am using filehelpers ExcelStorage somewhat like this:
ExcelStorage provider = new ExcelStorage(typeof(Img));
provider.StartRow = 2;
provider.StartColumn = 1;
provider.FileName = "Customers.xls";
provider.HeaderRows = 6;
provider.InsertRecords(imgs.ToArray()); // imgs was a list before
And when I am done inserting records, I would like to open the Excelfile I created (with my software still running). But it seems that Excel is somehow locked. I.e. there is an Excel instance running in process manager. When I kill all Excel instances I can open the file. Do I have to dispose the ExcelStorage in some sort of way?
I've used FileHelpers, but not ExcelStorage. The link here suggests that you should probably be using FileHelpers.ExcelNPOIStorage instead.
Looking at the source code for ExcelStorage, there is no public dispose method. There is a private CloseAndCleanup method which is called at the end of InsertRecords. Therefore I don't think there's anything you are doing wrong.
The usage of ExcelNPOIStorage looks very much the same, there is a call to GC.Collect() within the private cleanup method here, so I'd guess that there was a known issue with the cleanup of the prior version of the component.
Your best bet is to grab a copy of HANDLE.EXE which you can use with an elevated command prompt to see what has a handle to the file in question. This may be your code, anti virus or excel (if open). Excel does keep a full lock on a file when open preventing ordinary notepad access etc.
If the process owning the handle to the file is your own code, then see if the handle exists once you have exited back to the development environment. If that clears the handle, then you are not releasing the lock properly and that can be slightly trickier as it will depend on exactly what you have coded.
The CloseAndCleanup function mentioned by #timbo is only called from a few places, the Sheets property and the ExtractRecords / InsertRecords functions. The only other thing to wonder is whether you are seeing any exceptions when it attempts to perform the CloseAndCleanup or the reference count the Excel application hasn't been properly released by the COM system.
If you can replicate this with a small sample app, I will be more than willing to give it a quick test and see what happens.
Note 1, if you are running your code from within Visual Studio, it may be a process called <APPNAME>.VSHOST.EXE which is visual studio's development process, or if you've turned off Visual Studio hosting, just your <APP>.EXE. If running within IIS for a web page or web service, you will more than likely have a w3p process.
Note 2, if you run handle without being elevated, it may or may not find the handle to the file in question. Therefore, it is always recommended to run elevated to ensure results are accurate.
Note 3, the difference between ExcelStorage and ExcelNPOIStorage is that the former deals with .xls and the latter deals with .xlsx if I remember rightly.

rename a running application - dangerous?

I'm writing a small utility to update our application.
In order to update the update utility, I would like it to rename itself while running and copy the new version from a remote source. So the next time you start the updater, you have a new version.
Do you know of any possible problems which could occur, using that mechanismn?
Actually I was surprised it is at all possible to rename a running program (lost a cake there...), while deleting is not allowed.
Kind regards for any hints
using Win XP, .NET 3.5
You can rename - because it alters metadata only, but the actual file allocation chain is unmodified, which means they can stay memory-mapped in the process(es) that use it.
This is an ubiquitous trick in installers, when they have to upgrade 'live' running binaries.
It can cause trouble if the application tries to later reopen from the original filespecification. This is not something that regularly happens with executables or dlls, though you should be aware of embedded resources and programs that may do some self-certification (license checks). It's usually best to restart the corresponding application sooner than rather later, much like windows will urge you to reboot on system updates
Renaming an .exe is usually possible without any problems - renaming .dll's is quite another story.
I'd suggest using subdirectories instead (labeled with the date or version number) and creating a small launcher application (with the same name and icon as your "real" application) that reads the current version from a text file and launches it.
i.e.
updater.exe (the launcher)
updater.config (containing /updater_v_02/updater.exe)
/updater_v_01/updater.exe (the real app, v 01)
/updater_v_02/updater.exe (the real app, v 02)
This way, you can
keep several versions of your application around
test a new version (by directly launching it from the subdir) while your users continue using the old version
switch DLLs etc. without any hassle

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I'm hoping someone can enlighten me as to what could possibly be causing this error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I cannot really post code because this error seems to get thrown in any random area of the application. The application will run anywhere from 12-48 hours before throwing the error. Sometimes it will stop in a seemingly random spot and throw the above error, other times the entire application stops and I get a screen with an error that says something along the lines of "There was a fatal error in... This may be a bug in the CLR or..." something about PInvoke or other non relevant info. When this happens all threads show terminated and there is no debugging information available.
In a nutshell this is what the application does:
Its a multi-threaded server application written in entirely in C#. Clients connect to the server via socket. The server runs a virtual "environment" for the clients where they can interact with each other and the environment. It consumes quite a bit of memory but I do not see it leaking. It typically consumes about 1.5GB. I dont think its leaking because the memory usage stays relatively constant the entire time the application is running. Its constantly running code to maintain the environment even if the clients are not doing anything. It uses no 3rd party software or other APIs. The only outside resources this application uses is socket connections and SQL database connections. Its running on a 64bit server. I have tried debugging this in VS2008 & VS2010 using .net 2.0, 3.5, and 4.0 and on multiple servers and the problem still eventually occurs.
I've tried turning off compiler optimizations and several microsoft hot-fixes. Nothing seems to make this issue go away. It would be appreciated if anyone knows any possible causes, or some kind of way to identify whats causing the problem.
I have just faced this issue in VS 2013 .NET 4.5 with a MapInfo DLL. Turns out, the problem was that I changed the Platform for Build from x86 to Any CPU and that was enough to trigger this error. Changing it back to x86 did the trick. Might help someone.
I faced this issue with Visual Studio (VS) 2010. More interestingly, I had several types of projects in my solution namely a console application project, a WPF application project, a Windows Forms application project, etc. But it was failing only when, I was setting the Console Application type of project as start-up project of the solution. All the projects were completely empty. They had no user code or any 3rd party assemblies added as reference. All projects are referencing only the default assemblies of .NET base class library (BCL) which come with the project template itself.
How to solve the issue?
Go to project properties of the console application project (Alternately you can select the project file in solution explorer and press Alt + Enter key combination) > Go to Debug tab > Check the Enable unmanaged code debugging check box under Enable Debuggers section (refer screenshot) > Click Floppy button in the toolbar to save project properties.
Root cause of the issue is not known to me. Only thing I observed was that there were lot of windows updates which had got installed on my machine the previous night. All the updates constituted mostly of office updates and OS updates (More than a dozen KB articles).
Update: VS 2017 onward the setting name has changed to Enable native code debugging. It is available under Debugger engines section (refer screenshot):
The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved.
Finally tracked this down with the help of WinDBG and SOS. Access violation was being thrown by some unknown DLL. Turns out a piece of software called "Nvidia Network Manager" was causing the problems. I'd read countless times how this issue can be caused by firewalls or antivirus, neither of which I am using so I dismissed this idea. Also, I was under the assumption that it was not environmental because it occurs on more than 1 server using different hardware. Turns out all the machines I tested this on were running "NVidia Network Manager". I believe it installs with the rest of the motherboard drivers.
Hopefully this helps someone as this issue was plaguing my application for a very long time.
Try to run this command
netsh winsock reset
Source: https://stackoverflow.com/a/20492181/1057791
This error should not happen in the managed code. This might solve the issue:
Go to Visual Studio Debugger to bypass this exception:
Tools menu -> Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"
Hope it will help.
I got this error when using pinvoke on a method that takes a reference to a StringBuilder. I had used the default constructor which apparently only allocates 16 bytes. Windows tried to put more than 16 bytes in the buffer and caused a buffer overrun.
Instead of
StringBuilder windowText = new StringBuilder(); // Probable overflow of default capacity (16)
Use a larger capacity:
StringBuilder windowText = new StringBuilder(3000);
I've ran into, and found a resolution to this exception today. It was occurring when I was trying to debug a unit test (NUnit) that called a virtual method on an abstract class.
The issue appears to be with the .NET 4.5.1 install.
I have downloaded .NET 4.5.2 and installed (my projects still reference .NET 4.5.1) and the issue is resolved.
Source of solution:
https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception
It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.
What OS and service pack are you running?
I had this problem recently when I changed the development server for a project. I was getting this error on the line of code where I declared a new OracleConnection variable.
After trying many things, including installing hotfixes, I tried changing the references Oracle.DataAccess and System.Data.OracleClient in the project and it worked!
When a project is moved to a new machine, I suggest you renew all the references added in that project.
Did you try turning off DEP (Data Execution Prevention) for your application ?
Verifiable code should not be able to corrupt memory, so there's something unsafe going on. Are you using any unsafe code anywhere, such as in buffer processing? Also, the stuff about PInvoke may not be irrelevant, as PInvoke involves a transition to unmanaged code and associated marshaling.
My best recommendation is to attach to a crashed instance and use WinDBG and SOS to dig deeper into what's happening at the time of the crash. This is not for the faint of heart, but at this point you may need to break out more powerful tools to determine what, exactly, is going wrong.
I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)
Ok, this could be pretty useless and simply anecdotal, but...
This exception was thrown consistently by some Twain32 libraries we were using in my project, but would only happen in my machine.
I tried lots of suggested solutions all over the internet, to no avail... Until I unplugged my cellphone (it was connected through the USB).
And it worked.
Turns out the Twain32 libraries were trying to list my phone as a Twain compatible device, and something it did in that process caused that exception.
Go figure...
in my case the file was open and therefore locked.
I was getting it when trying to load an Excel file using LinqToExcel that was also opened in Excel.
this is all I deeded
var maps = from f in book.Worksheet<NavMapping>()
select f;
try {
foreach (var m in maps)
if (!string.IsNullOrEmpty(m.SSS_ID) && _mappings.ContainsKey(m.SSS_ID))
_mappings.Add(m.SSS_ID, m.CDS_ID);
} catch (AccessViolationException ex) {
_logger.Error("mapping file error. most likely this file is locked or open. " + ex);
}
I got the same error in a project I was working with in VB.NET. Checking the "Enable application framework" on the properties page solved it for me.
I had the same error message:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
In my case, the error went away after clean and re-build the solution.
Make sure you are not creating multiple time converter objects.
you can use to singleton class to create a converter object to resolve the below error with Haukcode.WkHtmlToPdfDotNet library
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
This issue is almost invariably a simple one. The code is bad. It's rarely the tools, just from a statistical analysis. Untold millions of people are using Visual Studio every day and maybe a few are using your code - which bit of code is getting the better testing? I guarantee that, if this were a problem with VS, we would probably already have found it.
What the statement means is that, when you try to access memory that isn't yours, it's usually because you're doing it with a corrupted pointer, that came from somewhere else. That's why it's stating the indication.
With memory corruption, the catching of the error is rarely near the root cause of the error. And the effects are exactly what you describe, seemingly random. You'll just have to look at the usual culprits, things like:
uninitialised pointers or other values.
writing more to a buffer than its size.
resources shared by threads that aren't protected by mutexes.
Working backwards from a problem like this to find the root cause is incredibly difficult given that so much could have happened between the creation of the problem and the detection of the problem.
I mostly find it's easier to have a look at what is corrupt (say, a specific pointer) and then do manual static analysis of the code to see what could have corrupted it, checking for the usual culprits as shown above. However, even this won't catch long chains of problems.
I'm not familiar enough with VS to know but you may also want to look into the possibility of using a memory tracking tool (like valgrind for Linux) to see if it can spot any obvious issues.
My answer very much depends on your scenario but we had an issue trying to upgrade a .NET application for a client which was > 10 years old so they could make it work on Windows 8.1. #alhazen's answer was kind of in the correct ballpark for me. The application was relying on a third-party DLL the client didn't want to pay to update (Pegasus/Accusoft ImagXpress). We re-targeted the application for .NET 4.5 but each time the following line executed we received the AccessViolationException was unhandled message:
UnlockPICImagXpress.PS_Unlock (1908228217,373714400,1341834561,28447);
To fix it, we had to add the following post-build event to the project:
call "$(DevEnvDir)..\tools\vsvars32.bat"
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\amd64\editbin.exe" /NXCOMPAT:NO "$(TargetPath)"
This explicitly specifies the executable as incompatible with Data Execution Prevention. For more details see here.
i had this problem too .
i was running different solutions at the same time using visual studio , when closing other solutions and running just the target solution , it worked fine without that error .
Got this error randomly in VS1017, when trying to build a project that was building perfectly fine the day before. Restarting the PC fixed the issue worked (I also ran the following command beforehand, not sure if it's required: netsh winsock reset)
In my case I had to reference a C/C++ library using P/Invoke, but I had to ensure that the memory was allocated for the output array first using fixed:
[DllImport("my_c_func_lib.dll", CharSet = CharSet.Ansi)]
public static extern unsafe int my_c_func(double input1, double input2, double pinput3, double *outData);
public unsafe double[] GetMyUnmanagedCodeValue(double input1, double input2, double input3)
{
double[] outData = new double[24];
fixed (double* returnValue = outData)
{
my_c_func(input1, input2, pinput3, returnValue);
}
return outData;
}
For details please see: https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/
In some cases, this might happen when:
obj = new obj();
...
obj.Dispose(); // <----------------- Incorrect disposal causes it
obj.abc...
This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.
[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
Running Visual Studio "as Administrator" solved the problem for me.
In my case the FTDI utility FT Prog was throwing the error as it scanned for USB devices. Unplugging my Bluetooth headphones from the PC fixed the issue.
I got this error message on lambda expression that was using Linq to filter a collection of objects. When I inspected the collection I noticed that its members weren't populated - in the Locals window, expanding them just showed "...". Ultimately the problem was in the repository method that initially populated the collection - Dapper was trying to automatically map a property of a nested object. I fixed the Dapper query to handle the multi-mapping and that fixed the memory error.
This may not be the best answer for the above question, but the problem of mine was invalid dispose syntax and usage of lock(this) for a buffer object. It turned out the object was getting disposed from another thread because of "using" syntax. And the processing lock() was on a loose type.
// wrong lock syntax
lock(this) {
// modify buffer object
}
I changed the locks to
private static readonly object _lockObject = new object();
lock(_lockObject) {
// modify buffer object
}
And used suggested C# disposing syntax and the problem gone.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any managed objects here
buffer?.Free();
}
disposed = true;
}
I've experienced the same issue when running a .Net Framework Web API application locally under IIS.
The issue was that I had previously updated the IIS App Pool's Managed Pipeline Mode to 'Classic'. Setting it back to 'Integrated' fixed the issue for me.
For Xamarin Forms one can wrap the code in
Device.BeginInvokeOnMainThread(() =>
{
//your code
});
Happened for me in UWP when updating UI from the wrong thread.

Categories