Custom time class being frozen when requesting date time

I'm working with a simple ASMX web service that gives the users the ability to add comments. For each comment that gets added I add a timestamp to the row. The issue I'm running into is that If I add two comments 1 second apart they will both have the same timestamp. Instead of using DateTime.Now in my code I use a static class so I can easily write unit tests.

Here is my Time class:

public class Time : IDisposable
{
    public static DateTime Now;

    static Time()
    {
        ResetToDefault();
    }

    public static IDisposable Freeze(DateTime dateTimeToFreeze)
    {
        Now = dateTimeToFreeze;

        return new Time();
    }

    void IDisposable.Dispose()
    {
        ResetToDefault();
    }

    private static void ResetToDefault()
    {
        Now = DateTime.Now;
    }
}

I'm guessing this class is the culprit because if I replace all instances of Time.Now with DateTime.Now everything works as expected.

What is causing my Time class to freeze and not always refresh when requesting the current time?

Answers


The public Now variable in your class is only updated when you call one of the methods Freeze or ResetToDefault.Accessing the variable itself will just get you the last updated value. In contrast, the Now property of DateTime always returns a value reflecting the current time.


Essentially, the static stuff is your problem. Static methods can cause real headaches for multi-threaded stuff too, because of the way that static vars (or classes with static constructors) remain in memory. You might be better off using a static function named Now() instead of a static var.


Need Your Help

css styling the facebook Login Button, best practices

javascript css facebook iframe

I am using the Facebook Login Button for Single Sign On in my webapp (code below). But I can't figure out how to control the button's styles with css. I see the Facebook plugin inserts an iframe in...