如何与定时抬高事件? [英] how to raise event with timer?

查看:128
本文介绍了如何与定时抬高事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行,所以我都有两个班,设定在不同的时间间隔定时器。人去关闭每2秒,其它每2分钟。每个代码计时器下运行的时候,我想它的代码生成数据的字符串引发事件。然后我想再拍类预订来自其他类的事件参数和不喜欢的东西,只要写一个事件被激发到控制台。而因为一个类只触发每2分钟这个类可以在最后一个事件存储在私人领域和重用,直到一个新的事件每次触发更新该值。



那么,我怎么引发的事件与数据的串?以及如何订阅这些事件并打印到屏幕或东西吗?



这是我到目前为止:

 公共类输出
{
公共静态无效的主要()
{
//使用引发的事件东西在这里
}
}


//第一个定时器
公共部分类FormWithTimer:EventArgs的
{
定时器定时器=新的Timer();

公共FormWithTimer()
{
定时器=新System.Timers.Timer(200000);

timer.Elapsed + =新ElapsedEventHandler(timer_Tick); //每次计时器滴答,timer_Tick将被称为
timer.Interval =(200000);
timer.Enabled = TRUE; //启用定时器
timer.Start(); //启动定时器
}

//运行该代码每隔2分钟,现在我只是有它运行的方法
//(CheckMail();)的所以它直接运行的代码代码,但我可以很容易地修改它。
无效timer_Tick(对象发件人,EventArgs五)
{
CheckMail();
}

公共静态字符串CheckMail()
{
字符串结果=0;


{
VAR URL = @https://gmail.google.com/gmail/feed/atom
VAR USER =USR;
VAR PASS =PSS

变种编码= TextToBase64(USER +:+ PASS);

VAR myWebRequest = HttpWebRequest.Create(URL);
myWebRequest.Method =POST;
myWebRequest.ContentLength = 0;
myWebRequest.Headers.Add(授权,基本+编码);

VAR响应= myWebRequest.GetResponse();
VAR流= response.GetResponseStream();

的XmlReader读卡器= XmlReader.Create(流);
System.Text.StringBuilder GML =新System.Text.StringBuilder();
,而(reader.Read())
如果(reader.NodeType == XmlNodeType.Element)
如果(reader.Name ==FULLCOUNT)
{$ B $ ; b gml.Append(reader.ReadElementContentAsString())附加(,);
}
Console.WriteLine(gml.ToString());
//我想提出的字符串GML在事件
}
赶上(例外EE){Console.WriteLine(ee.Message); }
返回结果;
}

公共静态字符串TextToBase64(字符串sAscii)
{
System.Text.ASCIIEncoding编码=新System.Text.ASCIIEncoding();
字节[]字节= encoding.GetBytes(sAscii);
返回System.Convert.ToBase64String(字节,0,bytes.Length);
}
}


//第二个定时器
公共部分类FormWithTimer2:EventArgs的
{
定时器定时器=新定时器();

公共FormWithTimer2()
{
定时器=新System.Timers.Timer(2000年);

timer.Elapsed + =新ElapsedEventHandler(timer_Tick); //每次计时器滴答,timer_Tick将被称为
timer.Interval =(2000年); //定时器将埃弗特打勾10秒
timer.Enabled = TRUE; //启用定时器
timer.Start(); //启动定时器
}

//运行该代码使用每2秒
无效timer_Tick(对象发件人,EventArgs五)
{
( var文件= MemoryMappedFile.OpenExisting(AIDA64_SensorValues))
{
使用(VAR readerz = file.CreateViewAccessor(0,0))
{
变种字节=新字节[ 194];
变种编码= Encoding.ASCII;
readerz.ReadArray&所述;字节>(0,字节,0,bytes.Length);

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

StringReader stringz =新StringReader(encoding.GetString(字节));

变种readerSettings =新的XmlReaderSettings {ConformanceLevel = ConformanceLevel.Fragment};使用(VAR读卡器= XmlReader.Create(stringz,readerSettings))
{
System.Text.StringBuilder阿依=新System.Text.StringBuilder()
;
,而(reader.Read())
{
使用(VAR fragmentReader = reader.ReadSubtree())
{
如果(fragmentReader.Read())
{
reader.ReadToFollowing(值);
//Console.WriteLine(reader.ReadElementContentAsString()+,);
aida.Append(reader.ReadElementContentAsString())附加(,);
}
}
}
Console.WriteLine(aida.ToString());
//我想提出的字符串阿依达在事件
}
}
}
}


解决方案

首先,我会做一个具有处理有关事件的逻辑基类。下面是一个例子:

  ///<总结> 
///继承这个类,你会得到人们可以subsribe
///来加一个简单的方法,以提高该事件的事件。
///< /总结>
公共抽象类BaseClassThatCanRaiseEvent
{
///<总结>
///这是一个自定义EventArgs类暴露一个字符串值
///< /总结>
公共类StringEventArgs:EventArgs的
{
公共StringEventArgs(字符串值)
{
值=价值;
}

公共字符串值{获得;私人集; }
}

//事件本身,人们可以订阅
公共事件的EventHandler< StringEventArgs> NewStringAvailable;

///<总结>
///辅助方法提高与给定的字符串
///<事件; /总结>
保护无效的RaiseEvent(字符串值)
{
变种E = NewStringAvailable;
如果(E!= NULL)
E(这一点,新StringEventArgs(值));
}
}

这是类声明的自定义EventArgs类暴露字符串值和引发事件的一个辅助方法。一旦您更新计时器从该类继承,你就可以做这样的事情:

 的RaiseEvent(aida.ToString ()); 

您可以订阅这些事件,如在.net中任何其他事件:

 公共静态无效的主要()
{
变种定时器1 =新FormWithTimer();
变种定时器2 =新FormWithTimer2();

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

//同为定时器2
}

静态无效timer1_NewStringAvailable(对象发件人,BaseClassThatCanRaiseEvent.StringEventArgs E)
{
VAR theString = e.Value;

//要带的东西theString,从计时器1
Console.WriteLine来了(刚拿到+ theString);
}


ok so i have two classes each with timers set at different intervals. one goes off every 2 seconds, the other every 2 minutes. each time the code runs under the timer i want it to raise an event with the string of data the code generates. then i want to make another class that subscribes to the event args from the other classes and does something like write to console whenever an event is fired. and since one class only fires every 2 minutes this class can store the last event in a private field and reuse that every time until a new event is fired to update that value.

So, how do i raise an event with the string of data?, and how to subscribe to these events and print to screen or something?

this is what i have so far:

    public class Output
    {
        public static void Main()
        {
            //do something with raised events here
        }
    }


    //FIRST TIMER
    public partial class FormWithTimer : EventArgs
    {
        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.Enabled = true;                       // Enable the timer
            timer.Start();                              // Start the timer
        }

      //Runs this code every 2 minutes, for now i just have it running the method        
      //(CheckMail();) of the code but i can easily modify it so it runs the code directly.
        void timer_Tick(object sender, EventArgs e)
        {
            CheckMail();             
        }

        public static string CheckMail()
        {
            string result = "0";

            try
            {
                var url = @"https://gmail.google.com/gmail/feed/atom";
                var USER = "usr";
                var PASS = "pss";

                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(",");
                        }
                Console.WriteLine(gml.ToString());
           // I want to raise the string gml in an event
            }
            catch (Exception ee) { Console.WriteLine(ee.Message); }
            return result;
        }

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


    //SECOND TIMER
    public partial class FormWithTimer2 : EventArgs
    {
        Timer timer = new Timer();

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

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

        //Runs this code every 2 seconds
        void timer_Tick(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(",");
                            }
                        }
                    }
                    Console.WriteLine(aida.ToString());
             // I want to raise the string aida in an event
                }
            }
        }
    }

解决方案

First, I would make a base class that has handles the logic relating to the event. Here is an example:

/// <summary>
/// Inherit from this class and you will get an event that people can subsribe
/// to plus an easy way to raise that event.
/// </summary>
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));
    }
}

That class declares a custom EventArgs class to expose the string value and a helper method for raising the event. Once you update your timers to inherit from that class, you'll be able to do something like:

RaiseEvent(aida.ToString());

You can subscribe to these events like any other event in .Net:

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

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

    //Same for timer2
}

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

这篇关于如何与定时抬高事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆