简体   繁体   中英

C# class property getting cached?

I have a class and am setting a UID as a class property because it is used in many methods throughout the program and I don't want to keep having to pass in a value to it. The issue I'm getting is that when I run context.Response.Write(uid) and refresh the page, I get the same value every time.

If I move createRandomString() to context.Response.Write(createRandomString()) , I get a new UID every time I reload.

I'm very new to using C# and coming from a PHP background, this is a bit odd for me. I would think that setting a class property would change every load. I'm thinking it probably has something to do with when the program is compiled, the UID is permanently set which still wouldn't make sense.

Code where property is getting set:

public class Emailer : IHttpHandler {
    // Define UID
    static string uid = createRandomString();

CreateRandomString Code:

public static string createRandomString() {
    Guid g = Guid.NewGuid();
    string GuidString = Convert.ToBase64String(g.ToByteArray());
    GuidString = GuidString.Replace("=", "");
    GuidString = GuidString.Replace("+", "");

    return GuidString;
}

Static fields are only instansiated once. That is why you always get the same result. Try this...

public class Emailer : IHttpHandler
{
    // Define UID
    string uid => createRandomString();
}

https://msdn.microsoft.com/en-us/library/aa645751(v=vs.71).aspx

Static class level members with an initialiser are only once the first time any memeber of the class (static or otherwise) is referenced.

The initialisation will only re-run when the assembly the class is contained in is unloaded from memory (eg when then executable is unloaded).

For an ASP application the assemblies are loaded and unloaded by the IIS process so you would fund that if you restarted the IIS process (for example) this would cause a new UID to be generated.

Solved it by keeping the fields static but setting the value upon load.

Fields:

// Define UID
static string uid = "";

// Define upload path for files
static string uploadPath = "";

Setting:

// Define UID
uid = createRandomString();
uploadPath = @"c:\" + uid + @"\";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM