C# XNA Weird error - c#

I've search google with no luck on this, maybe someone here could help as I really don't want to sign up on MSDN.
Every now and again I'll get this crash, I am not too sure what causes it.
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.Xna.Framework.Graphics.DeviceResourceManager.ReleaseAllReferences(UInt64 handle, Boolean dispose)
at Microsoft.Xna.Framework.Graphics.DepthStencilBuffer.ReleaseNativeObject(Boolean disposeManagedResource)
at Microsoft.Xna.Framework.Graphics.DepthStencilBuffer.!DepthStencilBuffer()
at Microsoft.Xna.Framework.Graphics.DepthStencilBuffer.Dispose(Boolean )
at Microsoft.Xna.Framework.Graphics.DepthStencilBuffer.Finalize()}
Using VS2008, C#, and XNA 3.1.
Edit: Here is the dispose code
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
TileSet.Dispose(); // Tileset is no longer needed.
blanksqaure.Dispose(); // Just for testing.
Logo.Dispose(); //D ispose logo.
AudioSystem.Dispose(); // Unload Audio System.
}

Since you say occasionally, is there a chance that sometimes an Update/Draw call runs after this dispose?
Are you sure these are not loaded by Content.Load? By the looks of these names, they sure do look like game assets probably loaded by Content manager

Related

Why I'm receiving Access Violation Exception when try to dispose VideoView in LibVLCSharp

I'm using Stylet as MVVM framework and LibVLCSharp.WPF 3.6.5 + VideoLAN.LibVLC.Windows 3.0.16 in my project for streaming camera rtsp streams.
VideoView is included in my VLCPLayer custom user control, and that control is exposed as a property in my view model. I don't know if this is a good thing, but in this way I managed to make some kind of custom full screen video with custom buttons.
Everything works fine until I try to close player, or better to say try to dispose VideoView.
I have something like this:
public void Dispose()
{
//these are custom events in my user control
VlcPlayer.ClosePlayer -= ClosePlayer;
VlcPlayer.RestorePlayer -= RestorePlayer;
VlcPlayer.MinimizePlayer -= MinimizePlayer;
//here I try to dispose player and VideoView
VlcPlayer.VideoView.MediaPlayer.Stop();
VlcPlayer.VideoView.MediaPlayer.Media.Dispose();
VlcPlayer.VideoView.MediaPlayer.Dispose();
//here I'm getting Access Violation Exception
VlcPlayer.VideoView.Dispose();
}
If I don't dispose VideoView it remains in memory and every time I start new stream new VideoView is added to memory, so if I opened and closed one stream and then opened the same or whatever stream, I'll have in memory 2 VideoViews instead of one. I have to release memory of unused VideoViews and players since application will be used for some kind of surveillance, so it will have lot of streams at the same time opened, and lot of VideoViews opened.
Here I found similar issue, but it was reportedly solved updating to newest version of LibVLCSharp, but my version is newer than from mentioned post and I still have similar problem.
I'd appreciate any kind of help on this issue. Thanks.

TransactionTooLargeException from Samsung's SmartClip service crashing my app - can it be intercepted?

Android Samsung phones have a SmartClip service that is invoked when a screenshot is taken. It launches an interface to immediately allow the screenshot to be edited.
My app will often crash when this action is performed, specifically when a large number of objects are drawn on the screen. This is a Xamarin.Forms app.
When the crash occurs, two threads are reported as responsible, with the following stack traces:
android.os.BinderProxy.transactNative BinderProxy.java
android.os.BinderProxy.transact BinderProxy.java:605
com.samsung.android.content.smartclip.ISpenGestureService$Stub$Proxy.sendSmartClipRemoteRequestResult ISpenGestureService.java:910
com.samsung.android.content.smartclip.SpenGestureManager.sendSmartClipRemoteRequestResult SpenGestureManager.java:77
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.sendResult SmartClipRemoteRequestDispatcher.java:654
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.dispatchScrollableAreaInfo SmartClipRemoteRequestDispatcher.java:313
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.access$100 SmartClipRemoteRequestDispatcher.java:59
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher$2.run SmartClipRemoteRequestDispatcher.java:154
android.os.Handler.handleCallback Handler.java:938
android.os.Handler.dispatchMessage Handler.java:99
android.os.Looper.loop Looper.java:246
android.app.ActivityThread.main ActivityThread.java:8512
java.lang.reflect.Method.invoke Method.java
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run RuntimeInit.java:602
com.android.internal.os.ZygoteInit.main ZygoteInit.java:1130
com.samsung.android.content.smartclip.SpenGestureManager.sendSmartClipRemoteRequestResult SpenGestureManager.java:81
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.sendResult SmartClipRemoteRequestDispatcher.java:654
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.dispatchScrollableAreaInfo SmartClipRemoteRequestDispatcher.java:313
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.access$100 SmartClipRemoteRequestDispatcher.java:59
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher$2.run SmartClipRemoteRequestDispatcher.java:154
android.os.Handler.handleCallback Handler.java:938
android.os.Handler.dispatchMessage Handler.java:99
android.os.Looper.loop Looper.java:246
android.app.ActivityThread.main ActivityThread.java:8512
java.lang.reflect.Method.invoke Method.java
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run RuntimeInit.java:602
com.android.internal.os.ZygoteInit.main ZygoteInit.java:1130
So... what do I do? This is a crash originating in third party code that I'm not including myself. Is there a hook somewhere that I can prevent this action from executing, or to handle the exception without crashing my app?
The only other solution would be to reduce the number of objects displayed so it comes under the 1 Mb limit, but I'd like to avoid that.
EDIT to add: Unfortunately, it looks like UnhandledException handling is not going to suffice, it was only meant for logging information about the crash.
Thanks to #ToolmakerSteve I have a workaround.
I used the information in the links to detect this exception and restart the activity:
# in MainApplication.cs
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if ((e.ExceptionObject as RuntimeException)?.InnerException is TransactionTooLargeException)
{
Intent intent = new Intent(ApplicationContext, typeof(MainActivity));
intent.AddFlags(ActivityFlags.NewTask);
StartActivity(intent);
}
}
}
Trying to do any state-saving action in this method fails. You have to rely on state that's saved prior to the crash. Luckily I already had such a mechanism.
So I just needed to detect a crash on startup (I used AppCenter's Crashes.HasCrashedInLastSessionAsync() and run my state-restoring method. Though for some reason I could only run this check after populating MainPage. Doing it before risked a blank screen.
In addition to this, I implemented limits on the number of objects drawn on the screen, so that the crash happens less frequently.
This isn't the best answer because it would be better to stop the third party code from crashing apps, but I hope it helps someone else.

Audio disposing problems using AudioVideoPlayback library

I'm trying to make playlist, where music plays one after another. I need to Dispose() Audio, when it finishes, because memory leak will occur. I wrote this code:
Audio a = new Audio(#"Music\Title.ogg");
a.Ending += new EventHandler((sender, e) => { (sender as Audio).Dispose(); });
a.Play();
The problem is that I have System.AccessViolationException in Application.Run(new MainForm());: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. It happens in ending event handler right after music finishes playing.
So, how can I play some music files one after another and dispose previous audio afer it finishes?
Don't dispose Audio inside it's own event because this class may want to do some bookkeeping work after invoking your handler.
I don't know logic of your applications but here are some idea, try to call Open on this object inside event handler. It should be smart enough to dispose old data and load new.

How to avoid ReportViewer memory leak when navigating through many reports?

I am using Visual Studio 2013 to create a WPF Desktop application that have some report generation functionalities, I have about 30 report and the user can swich from a report to another. My problem is that each time I change ReportEmbeddedResource and then call the RefreshReport() methods, the memory increases, so if the user navigate through all the 30 report my app will consume about 130 Mb! I know that I have to release the Resources after each navigation, I googled about that but didn't find an answer; Here is my code
public MainWindow() // constructor
{
InitializeComponent();
this.reportViewer.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
InitDataSources();
}
private void InitDataSources()
{
//manager data source
mangerDataSource = new ReportDataSource();
mangerDataSource.Name = "ManagerDataSet";
mangerDataSource.Value = uow.Members.GetAll().
ToList().Where((s) => s.MemberType == MemmberTypes.Manager);
reportViewer.LocalReport.DataSources.Add(mangerDataSource);
//adding 2 other data sources
}
public void RenderReport(string reportKey)
{
reportViewer.Reset();
string path = "Manager";
if (reportKey.Contains("tea")) path = "Teacher";
if (reportKey.Contains("stu")) path = "Student";
reportViewer.LocalReport.ReportEmbeddedResource = string.Format(
"Printers.Reports.{0}.{1}.rdlc", path,reportKey);
reportViewer.RefreshReport();
}
Is there a way to release the old report resource after Rendering a new report?
I don't have much experience with this but it seems that the best thing you can do is to use the Safe Handles to get your reports inside a manageable wrapper and then use the Dispose method and force the Garbage Collector to collect, while suppressing the Finalizer. Note that the memory usage you see in the Taskmanager is reserved memory, not actually memory in current use; it is possible that you release the report object and the taskmanager continues to report high memory values on the executable.
reportViewer.Dispose();
GC.SuppressFinalize(reportViewer);
The whole Disposing Method can become quite confusing so take your time and have a look here:
MSDN - Implementing a Dispose Method
MSDN - IDisposable.Dispose Method
I was having the same issue with .NET 4.5 VS 2013
I tried several things, but what finally made it work was:
Compiling the project in x64 and using LocalReport.ReleaseSandBoxAppDomain()
I got part of the solution from here: Very High Memory Usage in .NET 4.0
Problem is solved by MarkJ_KY's comment at https://connect.microsoft.com/VisualStudio/feedback/details/527451/ms-report-viewer-memory-leak-any-update-fix-winforms-application
It might look a little complex but it is not. The idea is to create an AppDomain, do your reporting stuff in that domain and then unload the domain. When unloading all memory are released :-)
I have used that solution which solves the problem for me.

How do you stop SoundEffect from crashing XNA windows games when they are closed?

I am creating a game for windows in xna using Visual C# Express. In the game, there are six SoundEffect objects which regularly have their Play() methods called. The problem is that sometimes when the game is closed it crashes. It appears to happen whenever the window is closed while a soundeffect is playing. This is the message which pops up in Visual C#:
AccessViolationException was unhandled
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
There isn't any source available in visual studio to debug and when the "get general help for this exception" is clicked, a blank page pops up..
The code used looks a lot like the MSDN example. This looks like a problem that exists somewhere in the underlying framework somewhere, not my code. But of course I don't know for sure. This has happened many times.
http://msdn.microsoft.com/en-us/library/bb195053.aspx
Here are the complete exception details:
System.AccessViolationException was unhandled
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=Microsoft.Xna.Framework
StackTrace:
at Microsoft.Xna.Framework.Audio.AudioCallbackDispatcher.IsEventRegistered(EventType type)
at Microsoft.Xna.Framework.Audio.AudioCallbackDispatcher.UnregisterEvent(EventType type)
at Microsoft.Xna.Framework.Audio.KernelMicrophone.ShutdownCaptureEngine()
at Microsoft.Xna.Framework.Audio.MicrophoneUnsafeNativeMethods.ShutdownCaptureEngine()
at Microsoft.Xna.Framework.Audio.AudioRendererShutdownHandler.AppExitingEventHandler(Object sender, EventArgs args)
InnerException:
(I also have music playing via MediaPlayer, but I don't think it's related.)
EDIT: I seem to have found something which works, but it's kind of hackish and really shouldn't be necessary. I'm still open to any more elegant solutions.
Call this line in Game1.UnloadContent(). It will make sure (if your sound effects are all shorter than 3 seconds) that no sound is playing when the program actually closes.
System.Threading.Thread.Sleep(3000);
Make the SoundEffect object a class member and call the SoundEffect's Dispose() method on class deconstruction:
class MyClass
{
~MyClass()
{
effect.Dispose();
}
SoundEffect effect;
}
This should let the SoundEffect object clean itself up when you close the game. You can read about objects that are Disposable here: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
Can you make MyClass implement IDisposable and dispose of the SoundEffect in that method?
I think it's pretty safe to say that this is a bug in the framework. Because it's in the audio code, perhaps the framework is not handling something it's getting from a driver correctly. It's hard to say for sure.
Suffice to say that an AccessViolationException coming out of the framework is not "normal". It's almost certainly not your fault.
The function IsEventRegistered that the exception occurs in is an unsafe function. So it's likely that function is doing exactly what the exception says: it is accessing an invalid memory address.
The exception is coming from the shutdown code for audio capture (microphone), so are you doing anything with the microphone in your code? You could possibly experiment with using/not using the microphone and see what happens.
Also: does this happen when you run without the debugger attached? (Ctrl+F5)
As for fixing the problem: Your solution is not a bad work-around.
If you cannot afford to wait the three seconds, and you want to get your hands dirty and write some very questionable (semi-unportable, not-necessaraly-forward-compatible) code: You could use reflection to access the private properties of the audio system. Find the list of SoundEffectInstance objects that are created internally whenever you call SoundEffect.Play, and then stop those instances before you shutdown.
Or you could do effectively the same thing by never calling Play, but instead calling CreateInstance and managing fire-and-forget sound effects on your own. The downside is that this requires writing an awful lot of code!
I had the same problem and I did nulls for my sound collections in class finalizer(destructor). Works for me.
public class Audio
{
private ContentManager content;
public List<SoundEffectInstance> SoundInstance { get; private set; }
public AudioEmitter Emitter { get; set; }
public AudioListener Listener { get; set; }
public List<SoundEffect> Sound { get; set; }
public Audio(ContentManager content)
{
this.content = content;
Emitter = new AudioEmitter();
Listener = new AudioListener();
Sound = new List<SoundEffect>();
SoundInstance = new List<SoundEffectInstance>();
}
//set to null your sound instances and effects :D
~Audio()
{
Sound = null;
SoundInstance = null;
}
...

Categories