0
public class AuctionTimer : IDisposable
{
    public static readonly ConcurrentDictionary<string, AuctionTimer> Timers;

    private readonly Timer timer;

    static AuctionTimer()
    {
        Timers = new ConcurrentDictionary<string, AuctionTimer>();
    }

    private AuctionTimer(string AuctionID, int ExecutionTime)
    {
        this._AuctionID = AuctionID;
        timer = new Timer();
        TimeCount = ExecutionTime;
        timer.Interval = new TimerUtil().getAuctionInterval();
        timer.Elapsed += (s, e) => MonitorElapsedTime();
        timer.Start();
    }

    private int TimeCount { get; set; }

    private string _AuctionID { get; set; }

    public static void StartTimer(string AuctionID, int ExecutionTime)
    {
        var newTimer = new AuctionTimer(AuctionID, ExecutionTime);
        if (!Timers.TryAdd(AuctionID, newTimer))
        {
            newTimer.Dispose();
        }
    }

    public static void StopTimer(string AuctionID)
    {
        AuctionTimer oldTimer;
        if (Timers.TryRemove(AuctionID, out oldTimer))
        {
            oldTimer.Dispose();
        }
    }


    public void Dispose()
    {
        // Stop might not be necessary since we call Dispose
        timer.Stop();
        timer.Dispose();
    }

    private void MonitorElapsedTime()
    {
        if (TimeCount == new TimerUtil().getAuctionInterval())
        {
            StopTimer(_AuctionID);
            //do the other process in db 
        }
        else
        {
            TimeCount++;
        }
    }
}

Following is the code for my Auction Timer what i am trying to do here is making an auction storing starting and ending date so lets say an auction is going to last for 5 hours so the end date will be 5 hours from current time i am starting the Auction timer right after storing the end date for the auction it is working as expected but the problem i am facing now is the timer is bit delay from the end time around 2,3 minutes roughly that's means the process which is suppose to run immediately after the auction expires is running 2,3 minutes late i am not really sure what i am missing here.

4

1 回答 1

0

我能够使用这个框架解决这个问题。

于 2019-12-10T08:41:44.433 回答