开发者

how to use timers and events in C#?

ok so ive been working on a program. i has 3 classes. 2 of the classes have timers that repeat at different intervals and once one "cycle" of the timer is done it raises an event with a string as return. the 3rd class subscribes to the events from the other two timer classes and does something with teh strings like print to console.

but i cant get it to work, it compiles fine but it just opens a console and then closes it fast(with no output). do you guys see anything wrong?

thanks

CODE:

using System;
using System.Timers;
using System.Text;
using System.Xml;
using System.IO;
using System.IO.Ports;
using System.IO.MemoryMappedFiles;
using System.Net;

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);
        }

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

            //To something with 'theString' that came from timer 1
            Console.WriteLine("Just got: " + theString);
        }

  开发者_Go百科      static void timer2_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)
        {
            var theString2 = e.Value;

            //To something with 'theString2' that came from timer 2
            Console.WriteLine("Just got: " + theString2);
        }
    }

    public abstract class BaseClassThatCanRaiseEvent
    {
        /// <summary>
        /// This is a custom EventArgs class that exposes a string value
        /// </summary>
        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;

        /// <summary>
        /// Helper method that raises the event with the given string
        /// </summary>
        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)
        {
            var url = @"https://gmail.google.com/gmail/feed/atom";
            var USER = "usr";
            var PASS = "pass";

            var encoded = TextToBase64(USER + ":" + PASS);

            var myWebRequest = HttpWebRequest.Create(url);
            myWebRequest.Method = "POST";
            myWebRequest.ContentLength = 0;
            myWebRequest.Headers.Add("Authorization", "Basic " + encoded);

            var response = myWebRequest.GetResponse();
            var stream = response.GetResponseStream();

            XmlReader reader = XmlReader.Create(stream);
            System.Text.StringBuilder gml = new System.Text.StringBuilder();
            while (reader.Read())
                if (reader.NodeType == XmlNodeType.Element)
                    if (reader.Name == "fullcount")
                    {
                        gml.Append(reader.ReadElementContentAsString()).Append(",");
                    }
            RaiseEvent(gml.ToString());
            // Console.WriteLine(gml.ToString());

        }

        public static string TextToBase64(string sAscii)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] bytes = encoding.GetBytes(sAscii);
            return System.Convert.ToBase64String(bytes, 0, bytes.Length);
        }
    }


    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)
        {
            using (var file = MemoryMappedFile.OpenExisting("AIDA64_SensorValues"))
            {
                using (var readerz = file.CreateViewAccessor(0, 0))
                {
                    var bytes = new byte[194];
                    var encoding = Encoding.ASCII;
                    readerz.ReadArray<byte>(0, bytes, 0, bytes.Length);

                    //File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));

                    StringReader stringz = new StringReader(encoding.GetString(bytes));

                    var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
                    using (var reader = XmlReader.Create(stringz, readerSettings))
                    {
                        System.Text.StringBuilder aida = new System.Text.StringBuilder();
                        while (reader.Read())
                        {
                            using (var fragmentReader = reader.ReadSubtree())
                            {
                                if (fragmentReader.Read())
                                {
                                    reader.ReadToFollowing("value");
                                    //Console.WriteLine(reader.ReadElementContentAsString() + ",");
                                    aida.Append(reader.ReadElementContentAsString()).Append(",");
                                }
                            }
                        }
                        RaiseEvent(aida.ToString());
                        //Console.WriteLine(aida.ToString());
                    }
                }
            }
        }
    }
}


You are exiting your Main method (which will stop your application) without waiting for your results. Just add a Console.ReadLine() for it to wait:

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();
}


You program is closing as it finishes the Main method. To make your project not close you can add Console.ReadLine() at the end of the method


Your program ends when the Main() function exits. What you are doing inside the method is to initialize the timers and exit. You need to implement a mechanism to wait for some condition to exit like:

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); 
            while (NotExit()){
               Thread.Sleep(1000);
            }
        } 

This way you can implement some NotExit() method that will stop the main thread based on a certain condition (like: the user presses a key and so on). Just a good practice: before exiting, try to gently stop any running threads (each Timer tick creates a new thread) so the code that is executed for eack timer tick is run into a separate thread. A way to do it is to use the Join() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜