I have a third party library that sometimes causes the AccessViolationException. I've marked the culprit line. I'd really like this method to fail gracefully so that my calling code can try it again in a short time, but at the moment, this exception brings down the whole application.
public static PlayerModel GetModel(int instanceId)
{
try
{
// New player model.
PlayerModel model = new PlayerModel();
// Fill.
model._flakyLibrary = new FlakyLibrary(instanceId); // **Sometimes crashes**
model.instanceId = instanceId;
// Return the new player model.
return model;
}
catch
{
// Try again in a bit - the game is not fully loaded.
return null;
}
}
One thought I had was to start a child process to run this bit of logic and have that crash gracefully if it needs to - I don't know how to do this, let alone have one process return this kind of object (my custom PlayerModel) to another process. I have exhausted searching Google and Stack Overflow (maybe I'm asking the wrong questions?).
Solution
Huge thanks to Theodoros. I've added the following attributes to the above method. The exception is now being caught.
[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
[System.Security.SecurityCritical]
P.S - I'm still fascinated to know about the multiple process solution if anyone knows what I should be researching? Many thanks again.
Another edit: I found a solution to using multiple processes: NamedPipeServerStream.