Приложение будильника в .NET

Это только для забавы:

можно копировать Гибель 3 подхода в 2D, если Вы сначала делаете шаг для преобразования мозаик в строки. Например,

- - - - -
- X X X -
- X X - -
- X - - -
- - - - L

... был бы уменьшен в три строки, соединяющие углы твердого объекта в треугольнике.

Затем сделайте то, что Гибель делают 3 механизма: С точки зрения источника света рассмотрите каждую "стену", которая стоит перед светом. (В этой сцене только рассмотрели бы диагональную строку.) Для каждой такой строки, спроектируйте его в трапецоид, передний фронт которого является исходной строкой, стороны которой лежат на строках от источника света до каждой конечной точки, и чей назад далеко, мимо целой сцены. Так, это - трапецоид, который "указывает на" свет. Именно все пространство стена набирает свою тень. Заполните каждую мозаику в этом трапецоиде с темнотой.

Продолжаются через все такие строки, и Вы закончите с "шаблоном", который включает все мозаики, видимые от источника света. Заполните эти мозаики светлым цветом. Можно хотеть осветить мозаику немного меньше, поскольку Вы убегаете от источника ("затухание") или делаете другой необычный материал.

Повторение для каждого источника света в Вашей сцене.

11
задан MusiGenesis 29 September 2009 в 15:13
поделиться

6 ответов

Or, you could create a timer with an interval of 1 second and check the current time every second until the event time is reached, if so, you raise your event.

You can make a simple wrapper for that :

public class AlarmClock
{
    public AlarmClock(DateTime alarmTime)
    {
        this.alarmTime = alarmTime;

        timer = new Timer();
        timer.Elapsed += timer_Elapsed;
        timer.Interval = 1000;
        timer.Start();

        enabled = true;
    }

    void  timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(enabled && DateTime.Now > alarmTime)
        {
            enabled = false;
            OnAlarm();
            timer.Stop();
        }
    }

    protected virtual void OnAlarm()
    {
        if(alarmEvent != null)
            alarmEvent(this, EventArgs.Empty);
    }


    public event EventHandler Alarm
    {
        add { alarmEvent += value; }
        remove { alarmEvent -= value; }
    }

    private EventHandler alarmEvent;
    private Timer timer;
    private DateTime alarmTime;
    private bool enabled;
}

Usage:

AlarmClock clock = new AlarmClock(someFutureTime);
clock.Alarm += (sender, e) => MessageBox.Show("Wake up!");

Please note the code above is very sketchy and not thread safe.

11
ответ дан 3 December 2019 в 06:22
поделиться

Interesting, I've actually come across a very similar issue and went looking for a method in the .Net framework that would handle this scenario. In the end, we ended up implementing our own solution that was a variation on a while loop w/ Thread.Sleep(n) where n gets smaller the closer you get to the desired target time (logarithmically actually, but with some reasonable thresholds so you're not maxing the cpu when you get close to the target time.) Here's a really simple implementation that just sleeps half the time between now and the target time.

class Program
{
    static void Main(string[] args)
    {
        SleepToTarget Temp = new SleepToTarget(DateTime.Now.AddSeconds(30),Done);
        Temp.Start();
        Console.ReadLine();
    }

    static void Done()
    {
        Console.WriteLine("Done");
    }
}

class SleepToTarget
{
    private DateTime TargetTime;
    private Action MyAction;
    private const int MinSleepMilliseconds = 250;

    public SleepToTarget(DateTime TargetTime,Action MyAction)
    {
        this.TargetTime = TargetTime;
        this.MyAction = MyAction;
    }

    public void Start()
    {
        new Thread(new ThreadStart(ProcessTimer)).Start();
    }

    private void ProcessTimer()
    {
        DateTime Now = DateTime.Now;

        while (Now < TargetTime)
        {
            int SleepMilliseconds = (int) Math.Round((TargetTime - Now).TotalMilliseconds / 2);
            Console.WriteLine(SleepMilliseconds);
            Thread.Sleep(SleepMilliseconds > MinSleepMilliseconds ? SleepMilliseconds : MinSleepMilliseconds);
            Now = DateTime.Now;
        }

        MyAction();
    }
}
8
ответ дан 3 December 2019 в 06:22
поделиться

You could simply reset the timer duration each time it fires, like this:

// using System.Timers;

private void myMethod()
{
    var timer = new Timer { 
        AutoReset = false, Interval = getMillisecondsToNextAlarm() };
    timer.Elapsed += (src, args) =>
    {
        // Do timer handling here.

        timer.Interval = getMillisecondsToNextAlarm();
        timer.Start();
    };
    timer.Start();
}

private double getMillisecondsToNextAlarm()
{
    // This is an example of making the alarm go off at every "o'clock"
    var now = DateTime.Now;
    var inOneHour = now.AddHours(1.0);
    var roundedNextHour = new DateTime(
        inOneHour.Year, inOneHour.Month, inOneHour.Day, inOneHour.Hour, 0, 0);
    return (roundedNextHour - now).TotalMilliseconds;
}
2
ответ дан 3 December 2019 в 06:22
поделиться

You could create an Alarm class which has a dedicated thread which goes to sleep until the specified time, but this will use the Thread.Sleep method. Something like:

/// <summary>
/// Alarm Class
/// </summary>
public class Alarm
{
    private TimeSpan wakeupTime;

    public Alarm(TimeSpan WakeUpTime)
    {
        this.wakeupTime = WakeUpTime;
        System.Threading.Thread t = new System.Threading.Thread(TimerThread) { IsBackground = true, Name = "Alarm" };
        t.Start();
    }

    /// <summary>
    /// Alarm Event
    /// </summary>
    public event EventHandler AlarmEvent = delegate { };

    private void TimerThread()
    {
        DateTime nextWakeUp = DateTime.Today + wakeupTime;
        if (nextWakeUp < DateTime.Now) nextWakeUp = nextWakeUp.AddDays(1.0);

        while (true)
        {
            TimeSpan ts = nextWakeUp.Subtract(DateTime.Now);

            System.Threading.Thread.Sleep((int)ts.TotalMilliseconds);

            try { AlarmEvent(this, EventArgs.Empty); }
            catch { }

            nextWakeUp = nextWakeUp.AddDays(1.0);
        }
    }
}
1
ответ дан 3 December 2019 в 06:22
поделиться

What about System.Timers.Timer class ? See http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

-1
ответ дан 3 December 2019 в 06:22
поделиться

Я уже использовал это раньше с большим успехом:

Vb.net:

Imports System.Threading
Public Class AlarmClock
    Public startTime As Integer = TimeOfDay.Hour
    Public interval As Integer = 1
    Public Event SoundAlarm()
    Public Sub CheckTime()
        While TimeOfDay.Hour < startTime + interval
            Application.DoEvents()
        End While
        RaiseEvent SoundAlarm()
    End Sub
    Public Sub StartClock()
        Dim clockthread As Thread = New Thread(AddressOf CheckTime)
        clockthread.Start()
    End Sub
End Class

C #:

using System.Threading;
public class AlarmClock
{
    public int startTime = TimeOfDay.Hour;
    public int interval = 1;
    public event SoundAlarmEventHandler SoundAlarm;
    public delegate void SoundAlarmEventHandler();
    public void CheckTime()
    {
        while (TimeOfDay.Hour < startTime + interval) {
            Application.DoEvents();
        }
        if (SoundAlarm != null) {
            SoundAlarm();
        }
    }
    public void StartClock()
    {
        Thread clockthread = new Thread(CheckTime);
        clockthread.Start();
    }
}

Я не знаю, работает ли C #, но vb работает нормально .

Использование в VB:

Dim clock As New AlarmClock
clock.interval = 1 'Interval is in hours, could easily convert to anything else
clock.StartClock()

Затем просто добавьте обработчик событий для события SoundAlarm.

-2
ответ дан 3 December 2019 в 06:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: