IMethodCallMessage Args.Get() - FatalExecutionEngineError or AccessViolationException - c#

This line of code causes the exceptions shown below:
object arg = methodCallMessage.Args[i];
private static List<ParameterInformation> GetParameterInfoList( IMethodCallMessage methodCallMessage )
{
List<ParameterInformation> parameterInformationList = new List<ParameterInformation>();
// Note: This works even if a parameter's value is null.
for( int i = 0 ; i < methodCallMessage.ArgCount ; i++ )
{
string argName = methodCallMessage.GetArgName(i);
object arg = methodCallMessage.Args[i];
var parameterInformation = new ParameterInformation(argName, arg);
parameterInformationList.Add(parameterInformation);
}
return parameterInformationList;
}
Exception:
FatalExecutionEngineError: The runtime has encountered a fatal error. The address of the error was at 0x71b97e8d, on thread 0x2ef4. The error code is 0xc0000005. 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.
Or sometimes this exception:
AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This happens on more than one machine.
In the call stack, when I show external code, this is at the top:
mscorlib.dll!System.Runtime.Remoting.Messaging.Message.Args.get() + 0x5 bytes.
Any ideas why this is happening, or how to fix it?
Note: The code that calls this method has a lock placed around it, so it shouldn't be a threading/timing issue.

This is more of a work-around than an actual fix, but it works for this situation. The problem only occurs when being done in an async way. The code that started the process had this wrapped around it:
Task.Factory.StartNew(() =>
When I removed that, and just processed things synchronously, the problem went away.

Related

'System.NotSupportedException' in PresentationCore.dll appeared in Output panel [duplicate]

I implemented a C# application that recevies frame RGB at framerate of 30fps.
The event of frame arrive is managed with this code:
void client_ColorFrameReady(object sender, ColorFrameReadyEventArgs e)
{
mycounter++;
Console.WriteLine("new frame received: " + mycounter);
if (writer != null)
{
count++;
if (count % 2== 0)
{
using (var frame = BitmapImage2Bitmap(e.ColorFrame.BitmapImage))
using (var thumb = ResizeBitmap(frame, 320, 240))
{
writer.WriteVideoFrame(thumb);
}
}
}
else
{
writer.Close();
}
}
with the if condition I manage only one of two frames.
When my code call BitmapImage2Bitmap I obtain this exception:
The exception in english should be:
A first chance exception of type 'System.NotSupportedException' occurred in `PresentationCore.dll`
Additional information: BitmapMetadata is not available on BitmapImage.
The strange thing is that my application works "well" because the frames are correctly inserted in the output file.
I've read this, so the problem seems a bug in WPF framework.
This is by design. A first-chance exception notification doesn't mean that there's a problem. The relevant code inside the Create() method looks like this:
try
{
metadata = source.Metadata as BitmapMetadata;
}
catch (NotSupportedException)
{
}
In other words, the exception is expected and simply swallowed. Which is certainly very annoying since these exceptions do make the debugger stop when you have the Thrown checkbox checked in the Debug + Exception dialog. But it certainly is not a bug, this was intentionally written this way. Sometimes it is a lot cheaper to just let an exception be thrown and swallowing it instead of writing the code that prevents the exception. Especially when it gets unpractical to avoid the exception, the case with bitmaps since there are so many different kind of bitmap types. Some of which don't support metadata. Wherever this is done inside the framework code, it is almost always done to make the code faster. Speed is also an important aspect of code.
Feature, not a bug. Untick the Thrown checkbox to avoid seeing these exceptions.
I hope my answer help you,
I had using same code, but BitmapFrame.cs (at PresetationCore.dll) occur Exception when we are using BitmapFrame.Create(source).
So, I just Using other create function below one, which is Inner function of BitmpaFrame.Create,
BitmapFrame.cs
public static BitmapFrame Create(
BitmapSource source,
BitmapSource thumbnail,
BitmapMetadata metadata,
ReadOnlyCollection<colorcontext> colorContexts
)
we can get same result BitmapFrame.Create(source, null, null, null).
in your case,
enc.Frames.Add(BitmapImage.Create(bitmap, null, null, null));
thanks.
Running with .NET Framework 4.5, I had to change the similar line in the Microsoft SDK WPF Photo Viewer sample from
_image = BitmapFrame.Create(_source);
to
_image = BitmapFrame.Create(_source, BitmapCreateOptions.None, BitmapCacheOption.None);
to avoid the ConfigurationErrorsException. Things seem to be drifting under the hood...
I've come across this issue lately when dealing with images included in projects as Resources (BuildType=Resource in file properties). It seems to be some build related issue which makes the resources corrupt and causes what seems like random issues as WPF are loading them. Simply performing a clean/rebuild makes the error(s) go away. They may reappear when adding new images though but the same fix obviously applies.

C# WPF unhandled exception: how to make the most of it

I am quite new to WPF but find AMAZING to be able to trap any unhandled exception. I have put
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
in the constructor of my class. This leads me to trap it with
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
...
}
At first it didn't work but then I've seen that to make it work I have to run it in release and outside VS IDE. So that works.
What I'd like is to get as much as info as possible about what caused the exception. Possibly the exception type, the s/r, the line and whatever else is provided.
At the moment by doing
int a = 0;
int b = 3 / a;
and by putting
MessageBox.Show(e.ToString() + " " + sender.ToString());
I get:
so that's not the right way.
I know that I am not putting the necessary information in the question but I have searched through various answer but none reported what I need. If so it can be useful to save any data prior closing but not about closing but not to detected what caused the exception
What's more when I exit with
Environment.Exit(-1)
I find the process still running and that's a problem.
Here Terminate application after unhandled exception it says that I have to kill my process is it really the right way to close my application after an unhandled exception?
Thanks for any help
The actual exception that caused the application to crash is wrapped inside the DispatcherUnhandledExceptionEventArgs parameter.
Simply use e.Exception to get hold of it.
MessageBox.Show(e.Exception.ToString());
After displaying the exception, I would suggest allowing the application to continue by calling the base method:
base.OnUnhandledException(sender, e);
You may choose to mark the exception as handled of course, however in the case of when you are simply overriding this method to display the error, I would not count that as handled.

Can a try/catch block prevent an error from occuring?

I have some code in my application that throws an error every so often (System.AccessViolationException) - So I wrapped it in a try/catch block and set a debug point and logging method in the catch element. I've found that since I did this the error has stopped happening - the debug point is never hit and nothing is logged. As soon as I remove the try from around the code I get the error again. What could be causing this?
The code is pretty trivial:
try
{
var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height);
var f2 = new Crop(ViewRectangle);
lfu = f2.Apply(lfu);
lfu = f1.Apply(lfu);
}
catch (Exception ex)
{
MainForm.LogExceptionToFile(ex);//never hit
}
There could be a couple of options:
or MainForm.LogExceptionToFile(ex); does not work as it expected
or, if we are 100% sure in that method, probably injecting try/catch block introduces in the code flow that microscopic delay (due the more IL code to execute/control), which is necessary to not get AccessViolationException on that machine. Which means, that is absolutely possible that you will get that exception on some other machine.
A AccessViolation Exception can't be skipped or catched.
Every time this exception happens it would be thrown!

Fatal execution error when a file is opened, closed and disposed multiple times in C#

In a thread, a file is being opened, closed and disposed continuosly. Does this cause an issue ?
Here is the code
StreamWriter file1 = new StreamWriter(filepath4, true);
for (int i = 0; i < ChannelValueForTcp; i++)
{
file1.WriteLine(data[i]);
}
file1.WriteLine(data[data.Length-1]);
file1.WriteLine(data[data.Length - 2]);
file1.Close();
file1.Dispose();
Please help I am stuck. (This comes up randomly we are trying to run the code for 8 hours continuously.)
Edit:
No no other thread works or does anything associated with this file. It is being used only here.
There are other threads running, which are giving the same error but randomly after 45 minutes - 5 hours of testing.
Here is the c code. Please download it
[DllImport("ConsoleApplication2.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int main_c();
public string[] tcp(string peer, int port)
{
int i = main_c();//the c code writes to a file called akash.txt and returns = 0 if it is successful. Then I read the file and do some functions on it.
if (i == 0)
{
StreamReader objReader = new StreamReader("akash.txt");
Random crashes and FatalExecutionEngineError exceptions are normally associated with stack or heap corruption which can remain hidden until further down in your code. Ensure that you have marshalled all your C++ functions correctly using the right calling convention, parameter types and return types.
Microsoft specifies the probable cause of the message is:
The CLR has been fatally corrupted. This is most often caused by data corruption, which can be caused by a number of problems, such as calls to malformed platform invoke functions and passing invalid data to the CLR.
Judging from the code you've supplied, your declaration looks correct so it could be another function that you've marshalled that is causing an issue.
Ensure that your C++ code is stable and not the cause of the problem. I think that it might be associated with the deletion or filling of the 'res' buffer.
You could be compiling the DLL with a flag which sets the calling convention to something apart from __cdecl. You can verify this by right-clicking on the project > Properties > C/C++ > Advanced > Calling Convention.

new XmlSerializer(typeof(MyClass)) Causing Memory corruption?

I've got an application that loads an assembly dynamically:
Assembly asm = Assembly.Load("MyClass.DLL");
Type type = asm.GetType("MyClass");
MyClass runningAssembly = (MyClass)Activator.CreateInstance(type);
runningAssembly.start();
Once loaded and the start() method is called, this line of code is executed:
XmlSerializer deserializer = new XmlSerializer(typeof(MyClass));
And the following exception is thrown:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
I've been stumbling on the cause of this and haven't been able to get a grasp on it. Does anyone have any tips? I also cannot seem to trap this error... it blows right through the try/catch.
By the way, the error doesn't always happen. Sometimes in debug mode it works fine, but it seems like once it starts, it'll always happen even after restarting Visual Studio. A reboot clears it up and allows it to work at least once. It also happens when running from the compiled EXE.
EDIT
I tried the same thing but without loading the assembly dynamically. I called it as a class directly, i.e:
MyClass c = new MyClass();
c.start();
And the same problem persists, so it does NOT appear to be related to being loaded dynamically.
It is hard to now what causes the problems without knowing anything about MyClass. Whats in the constructor and especially what is in the start() method? Does the code have any unsafe code? If you are addressing unsafe memory you could very likely experience the described behavior.
If your start() method is starting a new thread and an exception is thrown on the new thread you will not catch it in a try/catch around the start method.

Categories