Safely Initialising a static variable to a file












2












$begingroup$


This might appear to be a trivial task, but I think it's not the case. My code originally looked like this:



class DataSetToPdf
{
static byte F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
// Code which uses F1
}
}


Util.GetFile simply reads the file and returns an array of bytes. For completeness, here it is:



class Util
{
public static byte GetFile( String path )
{
IO.MemoryStream ms = new IO.MemoryStream();
using( IO.FileStream f = IO.File.OpenRead( path) )
{
f.CopyTo( ms );
}
return ms.ToArray();
}
}


However, when using DataSetToPdf in a multi-threaded environment (IIS), I was sometimes ( but not always ) getting mysterious null reference exceptions, which I could not easily debug. However, what I believe what was happening is that the static method could be called before the initialisation is complete. Instead what appears to be is necessary is this:



class DataSetToPdf
{

static System.Object Locker = new System.Object();

static byte F1;

public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
lock( Locker )
{
if ( F1 == null )
{
F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
}
}
// Code which uses F1
}
}


Please review my updated code, was it wrong before, is it right now?










share|improve this question











$endgroup$








  • 2




    $begingroup$
    MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
    $endgroup$
    – Jesse C. Slicer
    13 hours ago






  • 1




    $begingroup$
    What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
    $endgroup$
    – Brad M
    12 hours ago








  • 2




    $begingroup$
    Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
    $endgroup$
    – Jesse C. Slicer
    12 hours ago










  • $begingroup$
    @BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
    $endgroup$
    – George Barwood
    12 hours ago






  • 1




    $begingroup$
    @GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
    $endgroup$
    – Brad M
    12 hours ago


















2












$begingroup$


This might appear to be a trivial task, but I think it's not the case. My code originally looked like this:



class DataSetToPdf
{
static byte F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
// Code which uses F1
}
}


Util.GetFile simply reads the file and returns an array of bytes. For completeness, here it is:



class Util
{
public static byte GetFile( String path )
{
IO.MemoryStream ms = new IO.MemoryStream();
using( IO.FileStream f = IO.File.OpenRead( path) )
{
f.CopyTo( ms );
}
return ms.ToArray();
}
}


However, when using DataSetToPdf in a multi-threaded environment (IIS), I was sometimes ( but not always ) getting mysterious null reference exceptions, which I could not easily debug. However, what I believe what was happening is that the static method could be called before the initialisation is complete. Instead what appears to be is necessary is this:



class DataSetToPdf
{

static System.Object Locker = new System.Object();

static byte F1;

public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
lock( Locker )
{
if ( F1 == null )
{
F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
}
}
// Code which uses F1
}
}


Please review my updated code, was it wrong before, is it right now?










share|improve this question











$endgroup$








  • 2




    $begingroup$
    MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
    $endgroup$
    – Jesse C. Slicer
    13 hours ago






  • 1




    $begingroup$
    What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
    $endgroup$
    – Brad M
    12 hours ago








  • 2




    $begingroup$
    Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
    $endgroup$
    – Jesse C. Slicer
    12 hours ago










  • $begingroup$
    @BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
    $endgroup$
    – George Barwood
    12 hours ago






  • 1




    $begingroup$
    @GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
    $endgroup$
    – Brad M
    12 hours ago
















2












2








2





$begingroup$


This might appear to be a trivial task, but I think it's not the case. My code originally looked like this:



class DataSetToPdf
{
static byte F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
// Code which uses F1
}
}


Util.GetFile simply reads the file and returns an array of bytes. For completeness, here it is:



class Util
{
public static byte GetFile( String path )
{
IO.MemoryStream ms = new IO.MemoryStream();
using( IO.FileStream f = IO.File.OpenRead( path) )
{
f.CopyTo( ms );
}
return ms.ToArray();
}
}


However, when using DataSetToPdf in a multi-threaded environment (IIS), I was sometimes ( but not always ) getting mysterious null reference exceptions, which I could not easily debug. However, what I believe what was happening is that the static method could be called before the initialisation is complete. Instead what appears to be is necessary is this:



class DataSetToPdf
{

static System.Object Locker = new System.Object();

static byte F1;

public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
lock( Locker )
{
if ( F1 == null )
{
F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
}
}
// Code which uses F1
}
}


Please review my updated code, was it wrong before, is it right now?










share|improve this question











$endgroup$




This might appear to be a trivial task, but I think it's not the case. My code originally looked like this:



class DataSetToPdf
{
static byte F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
// Code which uses F1
}
}


Util.GetFile simply reads the file and returns an array of bytes. For completeness, here it is:



class Util
{
public static byte GetFile( String path )
{
IO.MemoryStream ms = new IO.MemoryStream();
using( IO.FileStream f = IO.File.OpenRead( path) )
{
f.CopyTo( ms );
}
return ms.ToArray();
}
}


However, when using DataSetToPdf in a multi-threaded environment (IIS), I was sometimes ( but not always ) getting mysterious null reference exceptions, which I could not easily debug. However, what I believe what was happening is that the static method could be called before the initialisation is complete. Instead what appears to be is necessary is this:



class DataSetToPdf
{

static System.Object Locker = new System.Object();

static byte F1;

public static void Go( Data.DataSet ds, int ix, System.IO.Stream output )
{
lock( Locker )
{
if ( F1 == null )
{
F1 = Util.GetFile( "C:PdfFilesFreeSans.ttf" );
}
}
// Code which uses F1
}
}


Please review my updated code, was it wrong before, is it right now?







c#






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 min ago









t3chb0t

34.4k748118




34.4k748118










asked 13 hours ago









George BarwoodGeorge Barwood

4079




4079








  • 2




    $begingroup$
    MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
    $endgroup$
    – Jesse C. Slicer
    13 hours ago






  • 1




    $begingroup$
    What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
    $endgroup$
    – Brad M
    12 hours ago








  • 2




    $begingroup$
    Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
    $endgroup$
    – Jesse C. Slicer
    12 hours ago










  • $begingroup$
    @BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
    $endgroup$
    – George Barwood
    12 hours ago






  • 1




    $begingroup$
    @GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
    $endgroup$
    – Brad M
    12 hours ago
















  • 2




    $begingroup$
    MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
    $endgroup$
    – Jesse C. Slicer
    13 hours ago






  • 1




    $begingroup$
    What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
    $endgroup$
    – Brad M
    12 hours ago








  • 2




    $begingroup$
    Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
    $endgroup$
    – Jesse C. Slicer
    12 hours ago










  • $begingroup$
    @BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
    $endgroup$
    – George Barwood
    12 hours ago






  • 1




    $begingroup$
    @GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
    $endgroup$
    – Brad M
    12 hours ago










2




2




$begingroup$
MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
$endgroup$
– Jesse C. Slicer
13 hours ago




$begingroup$
MemoryStream is also an IDisposable-implementing class (it descends from Stream) and should be wrapped in a using construct just like FileStream is.
$endgroup$
– Jesse C. Slicer
13 hours ago




1




1




$begingroup$
What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
$endgroup$
– Brad M
12 hours ago






$begingroup$
What was the null reference exception? F1 could never be null, because MemoryStream.ToArray() never returns null. Ideally, F1 should be readonly, so I guess it's possible something else is setting it to null. My guess is the exception is unrelated.
$endgroup$
– Brad M
12 hours ago






2




2




$begingroup$
Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
$endgroup$
– Jesse C. Slicer
12 hours ago




$begingroup$
Also, File.ReadAllBytes() should be able to do what you want without the intermediate copy to memory stream.
$endgroup$
– Jesse C. Slicer
12 hours ago












$begingroup$
@BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
$endgroup$
– George Barwood
12 hours ago




$begingroup$
@BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation.
$endgroup$
– George Barwood
12 hours ago




1




1




$begingroup$
@GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
$endgroup$
– Brad M
12 hours ago






$begingroup$
@GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage.
$endgroup$
– Brad M
12 hours ago












0






active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213058%2fsafely-initialising-a-static-variable-to-a-file%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213058%2fsafely-initialising-a-static-variable-to-a-file%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'