InvalidOperationException in my Lazy<> value factory - c#

I have a class containing something like the following:
public static class Config
{
private static Lazy<ConfigSource> _cfgSrc = new Lazy<ConfigSource>(
() => { /* "ValueFactory" here... */ },
true);
public static ConfigSource ConfigSource
{
get { return _cfgSrc.Value; }
}
}
In accessing the ConfigSource property, I encountered this InvalidOperationException:
ValueFactory attempted to access the Value property of this instance.
I don't see anything in my "value factory" method that accesses the Value property. Is there anything else that could be triggering this exception? This problem only happens intermittently, but once it does, it takes resetting IIS to clear up the Exception (which appears to be cached once it occurs).

It turned out that this error only occurred when trying to inspect the Value property of the Lazy<> in the Visual Studio debugger. Doing so appeared to create a deadlock because the accessing of Value then seemed to hang the thread for a long time until the InvalidOperationException finally occurred. I could never intercept the original Exception, so I couldn't see the inner stacktrace.
I'm just chalking this up as a bug in Visual Studio or their implementation of Lazy<>.

This has also happened to me with circular dependencies, so if these steps lead you nowhere, try double checking the stacktrace and verifying that there are no circular dependencies.

ValueFactory attempted to access the Value property of this instance.
It may help somebody, I was able to fix that error by inspecting my entire ValueFactory procedure.
In my example, I was creating a simple model and the linked it with some other data but during the linking process I was accessing the Value property in a singleton and that caused the error.
So accessing the Value of a Lazy object inside the ValueFactory throws such an error.
As the error message is already indicating ;-)

The behavior of Lazy<T> is to cache exceptions thrown by the ValueFactory. This can lead to potentially confusing behavior due to the paucity of information given in the InvalidOperationException message. Microsoft was made aware of this issue through Connect, however, it is marked as Wont Fix as they feel there is enough information in the exception itself to diagnose the problem.
If there is an inner exception for the IOE you receive, it should (not saying it will) contain enough information to continue onwards. Another possibility is you have a try...catch blocks which rethrows exceptions (throw ex; instead of throw;), you will lose valuable information.

To make sure your exception isn't cached, use LazyThreadSafetyMode.PublicationOnly as a second parameter, instead of true.
Using true, you'll end up with a LazyThreadSafetyMode.ExecutionAndPublication. This will ensure only one thread enteres the ValueFactory method, but also ensures exceptions will be cached.
private static Lazy<ConfigSource> _cfgSrc = new Lazy<ConfigSource>(
() => { /* "ValueFactory" here... */ },
LazyThreadSafetyMode.PublicationOnly);
See the link sixlettervariables provided for more information.

When lazy loading a configuration, be sure to not call methods that need said configuration. This will recall the configuration loader which starts over the process, resulting in the described error.
In my case, I was logging the loadstate, while the logger required a configuration

Related

MethodAccessException on Task.CompletedTask property

I am working on a small wpf application and one of the users is getting the following exception:
System.MethodAccessException:
Attempt by method "xxx.HttpConfirmation.Invoke()" to access method "System.Threading.Tasks.Task.get_CompletedTask()" failed.
at xxx.HttpConfirmation.Invoke()
at xxx.RequestPipeline.<ProcessQueuedRequests>d__11.MoveNext()
According to MSDN documentation, such exception is thrown in the following situations:
A private, protected, or internal method that would not be accessible from normal compiled code is accessed from partially trusted code by using reflection.
A security-critical method is accessed from transparent code.
The access level of a method in a class library has changed, and one or more assemblies that reference the library have not been recompiled.
Task.get_CompletedTask() is public since its introduction and I am also not using reflection to access the property.
I also don't think that there is a problem with code security/transparency since only one user is having this issue.
The exception is thrown at the Task.CompletedTask line:
public class HttpConfirmation
{
public static Task Invoke()
{
using (var client = new WebClient())
{
try
{
// Send the request and don't wait for the response.
client.UploadStringTaskAsync("http://sampleUrl.com", string.Empty);
}
catch
{
// ignore
}
}
return Task.CompletedTask;
}
}
Any ideas on what may cause the exception?
The problem was that the customer had .NET 4.5.2 installed and the program targeted .NET 4.6.
Though I still have no clue as to why exactly System.MethodAccessException was thrown as none of the 3 documented situations for throwing this exception did happen.

Exception of type System.Exception is not handled

Preface: Please don't refer me to Elmah. I'm trying to understand the MVC exception system for myself, not just use someone else's system for it.
I'm playing with MVC's exception system for my own enrichment, and I've run into an odd exception. I've written an OnException method as follows:
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled == true)
{
return;
}
// log error
ErrorLog(filterContext);
// mark error as handled to prevent rethrow
filterContext.ExceptionHandled = true;
//show custom error page
ViewBag.Code = filterContext.Exception is HttpException ? ((HttpException) filterContext.Exception).GetHttpCode() : 500;
ViewBag.Exception = filterContext.Exception;
filterContext.Result = View("Error");
}
I throw it via a simple enough call in a toy controller:
if(something strange and bad happens)
{
throw new Exception("When in trouble or in doubt, run in circles, scream and shout.");
}
I tested the exception and got the following exception:
An exception of type System.Exception occurred and was not handled in user code.
The string I sent into the constructor enters the exception system as part of the error message. When I continue execution through the error, I get to the error page with that message, but I keep getting the previous error when I try to run the code. The inner exception detail is null and the rest of the exception detail is too sparse for me to be able to use it to figure out what's gone wrong, or I'd read that instead of ask here.
I suspect I'm getting this exception because I'm not letting the base class finish handling the original exception, but I'm afraid I'm not entirely sure why. I've read a variety of articles on exception handling, but I'm not running into anything (that I know of) that has explained to me whether one needs to let the base class finish handling the exception or whether the handling I've done is sufficient. I've seen custom handling that did either or neither.
Or, conversely, if my suspicions are incorrect and it's something else entirely, does anyone know what it might be? The situation in which this is being thrown is very simple, and it's unlikely that anything else could be affecting this.
Does anyone know why I could be getting this error?
The code that we can see looks fine, so I'm left thinking that the exception comes from your ErrorLog method that we can't see.
You might be getting errors because a file is still in use (are you disposing the file streams correctly?) or for a variety of other reasons.
Your OnException method overrides MVC's error handling mechanism so when an exception happens during exception handling all hell breaks loose. The MVC framework probably has a very high level try { ... } catch { ... } somewhere just to save the application from crashing but it can't give you much more information on what happened.
Make sure your visual studio debugger breaks when an exception is thrown (https://msdn.microsoft.com/en-us/library/x85tt0dd.aspx) and then execute your code. Take a look at the exception thrown and the code involved. You'll either find why that specific part breaks or you'll find the subject of your next StackOverflow question. ;)

How can I add a message to an exception without losing any information in C#?

I have the following code:
catch(Exception ex)
{
throw new FatalException("An error occurred while trying to load the XSLT file.", ex);
}
This unfortunately just swallows up the Exception. I can fix this by doing the following:
catch(Exception ex)
{
throw;
}
But I would still like to include the custom message for help with event logging.
How do I add this message to the exception without losing any information? (stack trace/debug symbols, etc.)
If you just need to add information to the original exception, such as a user-readable message or specific details that will be useful to you in tracking down the error but that won't be useful to the end user, you can make use of the Exception's Data property, which is a key/value pair dictionary.
We use this extensively in order to record information such as the report being executed or file that is being processed so that operations can determine what exactly was happening at the time of the error. The user doesn't need this detail since they are working directly with the cause of the failure.
You could also use this to pass a plain text message that makes sense to the user. The only issue is that you will have to perform some additional work in your logging framework or end-user interface in order to extract the data and make it useful to the consumer.
For example, you could do:
catch (Exception ex)
{
ex.Data.Add("UserMessage", "An error occurred while trying to load the XSLT file.");
throw;
}
Then in the client-side code, you could test to see if UserMessage exists and, if so, present it to the user instead of the Exception:
catch (Exception ex)
{
if (ex.Data.Contains("UserMessage"))
{
MessageBox.Show(ex.Data["UserMessage"].ToString());
}
else
{
MessageBox.Show(ex.Message);
}
}
That original Exception is still there.
When you do your Exception logging, the Exception that you receive will be the FatalException that you made with your message. The original Exception is in ex.InnerException. You can continue to cycle through InnerException until it's null to get all of the Stack Trace information, etc.
In short, don't.
I'm sure you could find some way of getting around this with some reflection, but I would strongly caution you against this. It goes against the original design of exceptions in .NET. Exceptions are not just there to help with logging, they provide information about the original cause of an application failure.
Using the first option is generally preferred as it maintains the stack trace of the original exception but allows you to provide additional information by wrapping it in a separate exception. In my own code, whenever I log exceptions, my logging function will recurse through the InnerException property to find every bit of useful information possible about the error.
Just in case someone needs a good answer. The key is to use AppDomain.CurrentDomain.FirstChanceException
The you can create a custom object with IDisposable to put all info in it. And if exception happens then FirstChanceException handler gets that info and populate Exception.Data.
Use Local Thread Storage to make it thread safe. Then down the line the code that catches it will get the data and log it.
Example:
using(MyCustomMessage.EnterToLocalStorage("Info for logging"") )
{
...code
...exception thrown
.... FirstChanceException examines local thread storage and get's "info for logging" and puts into Exception.Data.
}
//Dispose is called and all messages that were put into LocalStorage are removed.
//So if exception was not thrown before then it like nothing happened.
Google AsyncDiagnosticStack for a good example. https://github.com/StephenCleary/AsyncDiagnostics/blob/master/src/Nito.AsyncEx.AsyncDiagnostics/AsyncDiagnosticStack.cs

$exception is defined in "locals"

H
We have log utility function that we call pretty often and I wanted to spice it up by adding a call to Server.GetLastError() and if there is an error to log as well.
The log function is part of separate project so I tried to use HttpContext.Current.Server.GetLastError() (As I do for the Request, ServerVariables and Session properties).
During the testing I created simple exception:
int i=0, j=0;
try
{
int k = i / j;
}
catch (Exception E)
{
Tools.CooLog("in");
}
Tools.CooLog("out");
In order to find out if "HttpContext.Current.Server.GetLastError()" will return the exception when Tools.CooLog("out"); is called.
Instead I had two big surprises
1. In both of the calls HttpContext.Current.Server.GetLastError() returned null.
2. And maybe the weirdest is that during the first call of CooLog in the locals section I saw a bit of my young, handsome and PHP version - I saw that there is value called $exception and surprisingly it ha the exception that HttpContext.Current.Server.GetLastError() failed to retrieve!
So my questions are
1. Why the HttpContext.Current.Server.GetLastError() returns null ? (HttpContext.Current.Request.ServerVariables works fine)
2. Where that $exception comes from? is there a way to use it? (in the second call to CooLog the variable is undefined)
That is a special debugger variable. You cannot access it via code.
The reason you don't see it in the Watch window, is that the exception has either been:
Handled
or
The Application.Error event has not been fired yet.
$exception is just the exception that was the reason the debugger paused execution of your program. This is the same as the exception you can access in your catch block, in your case E.

Trying to understand exceptions in C#

I do not really use any try/catches in my code ever but I'm trying to break that habit and now get in to using exceptions.
I figure the most important place to have it in my application would be reading a file and I'm trying to implement that now but I'm unsure of the "best-practices" for doing so. Currently I'm doing something like this:
private void Parse(XDocument xReader)
{
IEnumerable<XElement> person = xReader.Descendants("Person").Elements();
foreach (XElement e in person)
personDic[e.Name.ToString()] = e.Value;
if (personDic["Name"] == null || personDic["Job"] == null || personDic["HairColor"] == null)
throw new KeyNotFoundException("Person element not found.");
}
But I am unsure if this is correct. I have this for handling it:
try
{
personsReader.Read(filename, persons);
}
catch (KeyNotFoundException e)
{
MessageBox.Show(e.Message);
return;
}
// Do stuff after reading in the file..
However when showing e.Message it just shows the generic KeyNotFoundException error message and not by custom error message. Also I'm not sure if in general I am going about this whole "exception handling stuff" properly. I do return in the catch because if the file is not read successfully obviously I just want to pretend like the user never tried to open a file and let him try again with another file.
Am I doing this properly? Again I am fairly new to using exceptions and I want to make it sure I got it down right before continuing on and applying this to the rest of my program.
Also, why do people say not to do catch (Exception e)? It seems like in this case I would want to do that because regardless of what error occurs when reading in a file, if there is an error, I want to stop reading the file, display the error message, and return. Wouldn't that always be the case? I can understand not wanting to handle Exception e if you would want to handle something differently based on the exception but in this case wouldn't I want to just handle the base exception class in case anything goes wrong?
You should catch exceptions when you can handle the condition and do something useful. Otherwise you should let it bubble up the call stack and perhaps someone above you can handle it. Some apps have unhandled exception handlers to handle it at the outer most layer but in general, unless you know you have some useful way to handle it, let it go.
In your case, you're handling not being able to read a resource and informing the user. You're handling it. Concerning the generic exception, one thing you can do is catch and re-throw a better exception. If you do that, make sure you incude the root cause exception as the inner exception. You can also trace or log the details if appropriate.
throw new MyGoodExceptionType ("Could not read file", e); // e is caught inner root cause.
Now the UI shows a good error and perhaps the inner root cause is in a log etc...
Some typical mistakes:
Handling exceptions deep in the stack in a generic library method: Remember that a common library function may get called in many different code paths. You likely don't have the context whether it should be handled and whether it's appropriate to handle it. the caller higher in the stack likely has context and knows whether it's safe to handle. Typically that means higher layers of code decide to handle. In lower layers, typically you let them flow.
Swallowing Exception: Some code catches exceptions (especially lower in the stack) and then the root condition just evaporates making it maddening to debug. Once agan, if you can handle it, do so. If not, let it go.
Exceptions should be exceptional: Don't use excpetions for flow control. For example, if you're reading a resource, don't try and read and then catch the exception and make a decision point. Instead, call ifexists, check bool and make decisions in your code. this especially helps when you set the debugger to break on exceptions. You should be able to run clean and if the debugger breaks, it should be a real issue. Having the debugger break constantly when debugging is problematic. I personally like throwing exceptions very rarely and always try to avoid for flow control.
Hope that helps.
Ok, first...
... This iss not KeynotFoundException, it should be ArgumentException.... the Argument provided is not valid.
The documentation clearly states:
The exception that is thrown when the key specified for accessing an element in a collection does
not match any key in the collection.
Compare that with:
The exception that is thrown when one of the arguments provided to a method is not valid
Now:
Also, why do people say not to do catch (Exception e)?
Becasue this swallows the exception and makes it impossible to have central error handling / logging in place. ONLY handle exception you expect, UNLESS it is a catch / close something or log it / rethrow (i.e. throw;). Then have a central appdomain handler that gets every uncaptured exceptin and logs it ;) It can not handle anything - because exceptions at that level are unexpected,. It should basically write the excption to a file and be done, possibly with a UI (application has t obe restartet).
As far as what you're doing, it looks mostly ok. I can't speak to whether or not you should be throwing exceptions at that particular point, but the throwing and catching is correctly done. As far as the message, it should be working the way it stands. Try displaying e.ToString() to see the call stack. It could be that simply doing person["Name"] is throwing the KeyNotFoundException first.
As to the question of catching Exception, it's not always bad. Sometimes you cannot predict all possible exceptions, and it's sometimes a good thing to handle any possible failure. However, it gives you no way to handle particular exceptions differently.
As an example, if you get KeyNotFoundException, you might mention something about how the file is incorrectly formatted, and maybe display the file to the user on the screen. If you get FileNotfoundException, you could show them the path and open up an OpenFileDialog to have them select a new file. Exceptions due to security permissions you could display instructions to have them elevate your permissions. Some exceptions may even be recoverable (perhaps one element is badly formatted, but the rest are ok; should it fail the whole thing?)
But, it's ok to catch everything if that's how you want to design it. The most solid program out there would catch every possible exception and handle it in very specific ways, instead of presenting the raw exception to the user. It makes for a better user experience, and gives you ways to work around the problems that can happen.
Most of the time you may not care about the type of exception you get so catching the generic Exception is fine, however there are specific situations in which you would actually want to catch the relevant exception (not just the generic Exception).
One particular example is if you have a thread and you want to interrupt it from a blocking call, in that case you have to distinguish between the InterruptException and the Exception.
Consider this example: you have a thread which runs the Read every minute for 5 minutes (it's not a very realistic example, but it should give you an idea of why you want to handle different exceptions). You have to stop the thread after 5 minutes because your application is going to shut down and you don't want to wait another minute for the running flag to be read... after all, you don't want your user to be waiting for an entire minute just to shut down the application. In order to stop the thread right away, you set the flag to false and you call Interrupt on your thread. In this case you specifically have to catch the ThreadInterrupted exception, because it tells you that you should exit the loop. If you catch another exception, then you've failed to perform the task, but you don't want to give up on the job all together and you would like to try and read again the next minute. This depicts how your requirements dictate the type of exceptions you need to handle. Here is the example in code:
bool running = true;
Thread t = new Thread(()=>
{
while(running)
{
try
{
// Block for 1 minute
Thread.Sleep(60*1000);
// Perform one read per minute
personsReader.Read(filename, persons);
}
catch (KeyNotFoundException e)
{
// Perform a specific exception handling when the key is not found
// but do not exit the thread since this is not a fatal exception
MessageBox.Show(e.Message);
}
catch(InterruptException)
{
// Eat the interrupt exception and exit the thread, because the user
// has signalled that the thread should be interrupted.
return;
}
catch(Exception e)
{
// Perform a genetic exception handling when another exception occurs
// but do not exit the thread since this is not a fatal error.
MessageBox.Show("A generic message exception: " + e.Message);
}
}
});
t.IsBackground = true;
t.Start();
// Let the thread run for 5 minutes
Thread.Sleep(60*5000);
running = false;
// Interrupt the thread
t.Interrupt();
// Wait for the thread to exit
t.Join();
Now on to your other problem with the exception not showing up: note that you're accessing person[e.Name.ToString()] = e.Value which requires a key lookup and if the key is not in the map, then you may get a KeyNotFoundException. That would be the generic exception that you're catching and your custom exception will never be thrown because person[e.Name.ToString()] may throw before you even get to your code.
foreach (XElement e in person)
person[e.Name.ToString()] = e.Value; // <-- May be throwing the KeyNotFoundException
if (person["Name"] == null || person["Job"] == null || person["HairColor"] == null)
throw new KeyNotFoundException("Person element not found.");
Furthermore, you don't want to throw a KeyNotFoundException when you've actually found the key but you didn't find a corresponding value: if person["Name"] == null evaluates to true, then the key "Name" was actually found in the person dictionary, so throwing the KeyNotFoundException would be misleading to anybody who catches that exception. In the case that your value is null, then it would probably not be advisable to throw an exception anyway... it really isn't an exceptional case. You could return a flag indicating that the key was not found:
public bool PerformRead(/*... parameters ...*/)
{
foreach (XElement e in person)
{
// Avoid getting the KeyNotFoundException
if(!person.ContainsKey(e.Name.ToString()))
{
person.Add(e.Name.ToString(), "some default value");
}
person[e.Name.ToString()] = e.Value;
}
if (person["Name"] == null || person["Job"] == null || person["HairColor"] == null)
{
return false;
}
else
{
return true;
}
}
I'm not quite sure why you're not getting your custom error message. That should be happening (unless it's something else throwing a KeyNotFoundException, not the one that you're explicitly throwing).
Also, generally you should put all the code that relies on the file read being successful inside the try, which is often the rest of the body of your method. You no longer would need a return inside your catch block, and subsequent code that doesn't rely on the file read being successful could still execute after a failure.
Example:
public static void Main()
{
var filename = "whatever";
try
{
personsReader.Read(filename, persons);
var result = personsReader.DoSomethingAfterReading();
result.DoSomethingElse();
}
catch (KeyNotFoundException e)
{
MessageBox.Show(e.Message);
}
finally
{
personsReader.CloseIfYouNeedTo();
}
DoSomeUnrelatedCodeHere();
}
And the reason it's good practice not to catch any old Exception e is because you only want to catch and handle the exceptions you're expecting to get. If you get a different kind of exception that you weren't expecting to get, typically this means that something novel failed in a way you didn't anticipate, and you want this behavior to be noticeable, not just get swept under the rug with all the regular error-handling code.
A lot of production-level systems will have one big try/catch around the entire program that catches any exception and performs logging and cleanup before crashing gracefully. This is complemented by having specific try/catch blocks deeper inside the code that handle expected exceptions in a well-defined manner. For unexpected exceptions, you could always just let the CLR bomb ungracefully and figure out what happened from that.
Here's an example of a novel exception. What if something goes terribly wrong and in this line:
IEnumerable<XElement> person = xReader.Descendants("Person").Elements();
...you get an OutOfMemoryException? Should you really just display a popup to the user and allow your program to try to carry on like normal, even though there's simply no way it will be able to? And what if, because you failed silently on an OutOfMemoryException, you later attempt to dereference a null reference, and get a NullReferenceException that causes your program to crash? You'll have a devil of a time trying to track down the root cause of why that reference was null.
Best way to suss out a bug is to fail fast and fail noisily.
"Exceptions are for Exceptional circumstances" - unknown
Don't use the to essentially pass a message out of a method to the calling method. Always try to gracefully handle things. When something really odd happens then throw an exception. This is something that dev not real familiar with how to use exceptions do a lot.
In your code you are triggering the xxx when you evaluate the condition inside the if statement.
Asking person["Name"] == null || person["Job"] == null || person["HairColor"] == null will fail if any of those keys are not in your dictionary.
You need to do this instead:
if (!person.ContainsKey("Name"] ||
!person.ContainsKey("Job"] ||
!person.ContainsKey("HairColor"))
So, your call to throw the exception is never executed! And that's why you never see your message.
I would keep your habit of not doing exceptions for this kind of coding. Exceptions are expensive and can cause real issues in your code to be hidden.
Don't catch general exceptions and don't create exceptions for non-exceptional circumstances.

Categories