Domanda

Ho lavorato a un programma. Ho 3 lezioni. 2 delle classi hanno timer che si ripetono a intervalli diversi e una volta che un "ciclo" del timer viene eseguito, solleva un evento con una stringa come ritorno. La terza classe si iscrive agli eventi delle altre due classi di timer e li stampa sullo schermo. Funziona alla grande!

Ma il mio problema è che li stampa separatamente. Supponiamo che attualmente la prima classe di timer corre e poi solleva "ciao" ogni 2 minuti e l'altro "cane" ogni secondo. Quindi ogni volta che viene sollevato un evento, stampa l'evento rialzato su console. Vorrei che stampino invece "Hellodog" ogni secondo.

Stavo pensando: quindi ogni volta che un timer si accende solleverà un evento e aggiornerà una stringa nella classe "output" con il valore corrente, quindi realizzerà un altro timer che si spegne ogni secondo, questo timer leggerà entrambe le stringhe aggiornate insieme come Un output come "Hellodog". È possibile se è questo il modo più semplice che penso. Come ottenere questa idea?

Se è confuso chiarirò.

namespace Final
{
    public class Output
    {
        public static void Main()
        {
            var timer1 = new FormWithTimer();
            var timer2 = new FormWithTimer2();

            timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);

            timer2.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer2_NewStringAvailable);
            Console.ReadLine();
        }

        static void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)
        {
            var theString = e.Value;

            //To something with 'theString' that came from timer 1
            Console.WriteLine(theString);
        }

        static void timer2_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)
        {
            var theString2 = e.Value;

            //To something with 'theString2' that came from timer 2
            Console.WriteLine(theString2);
        }
    }

    public abstract class BaseClassThatCanRaiseEvent
    {
        public class StringEventArgs : EventArgs
        {
            public StringEventArgs(string value)
            {
                Value = value;
            }

            public string Value { get; private set; }
        }

        //The event itself that people can subscribe to
        public event EventHandler<StringEventArgs> NewStringAvailable;

        protected void RaiseEvent(string value)
        {
            var e = NewStringAvailable;
            if (e != null)
                e(this, new StringEventArgs(value));
        }
    }

    public partial class FormWithTimer : BaseClassThatCanRaiseEvent
    {
        Timer timer = new Timer();

        public FormWithTimer()
        {
            timer = new System.Timers.Timer(200000);

            timer.Elapsed += new ElapsedEventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
            timer.Interval = (200000);             // Timer will tick evert 10 seconds
            timer.Enabled = true;                       // Enable the timer
            timer.Start();                              // Start the timer
        }

        void timer_Tick(object sender, EventArgs e)
        {
            ... 
            RaiseEvent(gml.ToString());                    
        }
    }


    public partial class FormWithTimer2 : BaseClassThatCanRaiseEvent
    {
        Timer timer = new Timer();

        public FormWithTimer2()
        {
            timer = new System.Timers.Timer(1000);

            timer.Elapsed += new ElapsedEventHandler(timer_Tick2); // Everytime timer ticks, timer_Tick will be called
            timer.Interval = (1000);             // Timer will tick evert 10 seconds
            timer.Enabled = true;                       // Enable the timer
            timer.Start();                              // Start the timer
        }

        void timer_Tick2(object sender, EventArgs e)
        {
            ...
            RaiseEvent(aida.ToString());
        }
    }
}
È stato utile?

Soluzione

Puoi utilizzare lo stesso gestore di eventi per entrambi i timer. E costruire l'output identificando i mittenti. (Non ha testato il codice per errori di sintassi.)

private static string timer1Value = string.Empty;
private static string timer2Value = string.Empty;
private static FormWithTimer timer1;
private static FormWithTimer2 timer2;

public static void Main()
{
    timer1 = new FormWithTimer();
    timer2 = new FormWithTimer2();

    timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);

    timer2.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);
    Console.ReadLine();
}


static void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)
{
    if (sender == timer1)
    {
        timer1Value = e.Value.ToString();
    }
    else if (sender == timer2)
    {
        timer2Value = e.Value.ToString();
    }

    if (timer1Value != String.Empty && timer2Value != String.Empty)
    {
        Console.WriteLine(timer1Value + timer2Value); 
        // Do the string concatenation as you want.
    }

Altri suggerimenti

Quando gli eventi vengono gestiti nel tuo esempio, non hanno accesso alle informazioni sugli altri eventi. Se vuoi avere 2 eventi che aggiornano stringhe, ma vuoi che il gestore stampino i dati Entrambi Stringhe aggiornate, hai bisogno che i gestori di eventi abbiano accesso a entrambe queste stringhe. Puoi archiviarli in variabili nella classe di gestione degli eventi o renderle proprietà pubbliche delle lezioni che stanno sollevando gli eventi. In questo modo in entrambi i gestori di eventi hai accesso alle stringhe aggiornate da altri eventi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top