You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jan 3, 2023. It is now read-only.
Repository navigation
This repository was archived by the owner on Jan 3, 2023. It is now read-only.
Unexpected NullReferenceException bug when using async functions from another assembly #326
Create an F# console application and an F# library.
Add a reference from the console application to the library project.
Replace the code Visual Studio generates with the following:
Code for the console application:
[<EntryPoint>]
let main argv =
WeirdBug.Bug.reproduce() |> Async.RunSynchronously
0 // return an integer exit code
Code for the library:
namespace WeirdBug
module Bug =
let nums = [|1;2;3|]
let reproduce () =
async {
for n in nums do // Why does this throw a nullreferenceexception?!?!
printfn "%d" n
}
Now compile/run and you should get an null reference exception. If you move the code from the library into the console application itself the error disappears.
Tested on VS2013, FSharp.Core 4.3.1.0, .NET 4.5, Windows 8.
It seems that the project type guids got muddled and my library project was actually also a console application (.exe). Changing this to a library (.dll) fixed the problem.
Not entirely sure why this should be an issue though, is there any reason a referenced assembly can't also be a .exe?
You should be able to reproduce the problem if you change the library project to a console application in project settings.
System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in FSharp.Core.dll
Additional information: Object reference not set to an instance of an object.
Ahh, yes that makes sense. When compiled as a console app, the compiler generates a main method, and initialization of nums is done there. When compiled as a library, initialization of nums is done in a generated static constructor. If you reference the console app like a library, main is never run, so nums is null when accessed. Unfortunately, main is tucked away in an internal class you can't really get to, so you can't work around by calling main explicitly.
You can work around by declaring an explicit dummy main in your exe, though:
moduleProgram =[<EntryPoint>]letmain _ =0
This forces the module initialization stuff to be put in a static constructor, like it would be if it were a library.
Not sure where this lands in terms of by-design vs bug. I agree it's unintuitive/annoying.
Repro:
Code for the console application:
Code for the library:
Now compile/run and you should get an null reference exception. If you move the code from the library into the console application itself the error disappears.
Tested on VS2013, FSharp.Core 4.3.1.0, .NET 4.5, Windows 8.