如何合并两个相似但独立的程序的 C# 代码? [英] how to merge C# code of two similar but separate programs?

查看:63
本文介绍了如何合并两个相似但独立的程序的 C# 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有两个程序.代码在最后.

ok so i have two programs. Code at end.

one 是一个 gmail 通知程序,它通过串行输出未读邮件的数量,例如:<02,> 等.

one is a gmail notifier that outputs the number of unread mails over serial like: <02,> etc.

然后我有一个程序可以获取系统(PC)温度并将它们输出到串行也像:<30,42,50,> etc

then i have a program that gets system(pc) temps and outputs them to serial also like: <30,42,50,> etc

它们在不同的时间间隔(每次都有不同的值)输出相同的数据和相同的格式().所以邮件每5分钟检查一次邮件,然后输出以序列化邮件的数量.但是临时程序在 1 秒内以更快的速度通过串行输出数据.

they both output the same data and same format(<XX,>) at different time intervals(with different values each time). so the mail one checks every 5 minutes for mail, then outputs to serial the number of mails. but the temp program outputs the data over serial at a much fater rate at 1 sec.

我一直在尝试将两个程序合二为一,以便输出如下:<02,30,42,50,> 并每秒发送一次,以便临时更新.所以最后三组数字每秒都会改变,但第一组不会每 5 分钟改变一次,但 02 仍然包含在输出中,因为它(输出)每次都需要相同的长度/组织等.

ive been trying to combine the two programs into one, so that it outputs like: <02,30,42,50,> and it sends that every second so that the temps update. so the last three sets of digts change every second, but the first one wont change for every 5 minutes but 02 is still included in the output because it(the output) needs to be the same length/organization etc every time.

你们觉得呢?最好的方法是什么?

so what do you guys think? what is the best way to do it?

我尝试将除static void Main之外的所有GMAIL代码(在gmail程序中Main所做的所有工作都是调用get mail并将数据写入串行)到TEMPS程序,然后调用getmail Unreadz = CheckMail(); 其中临时程序正在写入串行(在新的组合代码中),但这会停止向串行写入数据,以便它可以检查邮件,这有点慢,所以它不会写整个 <02,30,42,50,> 直到邮件完成检查.我的尝试:

ive tried to add all the GMAIL code except static void Main (all Main does in the gmail program is call get mail and write the data to serial) to the TEMPS program, and then call the getmail Unreadz = CheckMail(); where the temps program is writing to serial(in the new combined code), but that stops the writing of data to serial so that it can check mail, which is kinda slow, so then it deosnt write the whole <02,30,42,50,> until mail is done checking. my attempt:

reader.ReadToFollowing("value");
port.Write(reader.ReadElementContentAsString() + ",");
Unreadz = CheckMail();
if (Convert.ToInt32(Unreadz) < 10) port.Write("0" + Unreadz + ",");
else port.Write("" + Unreadz + ",");

谢谢.

GMAIL:

namespace GmailNotifier
{
    class Gmail
    {
        public static void Main(string[] args)
        {
            try 
            {
               SerialPort port = new SerialPort( "COM2", 9600, Parity.None, 8, StopBits.One );
               port.Open();

                string Unreadz = "0";
                while ( true )
                {
                    Unreadz = CheckMail();

                    port.Write("<");

                    Console.WriteLine("Unread Mails: " + Unreadz);
                    if (Convert.ToInt32(Unreadz) < 10) port.Write("0" + Unreadz + ",");
                    else port.Write("" + Unreadz + ",");

                    port.Write(">");

                    System.Threading.Thread.Sleep(1000);
                }
            } catch ( Exception ee ) { Console.WriteLine( ee.Message ); }

        }

        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 static string CheckMail() 
        {
            string result = "0";

            try 
            {
                var url = @"hsttps://gmail.google.com/gmail/feed/atom";
                var USER = <uname>;
                var PASS = <password>;

                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 );
                while ( reader.Read())
                    if ( reader.NodeType == XmlNodeType.Element )
                        if ( reader.Name == "fullcount" ) 
                        {
                            result = reader.ReadElementContentAsString();
                            return result;
                        }
            } catch ( Exception ee ) { Console.WriteLine( ee.Message ); }
              return result;
        }

    }
}

温度:

namespace AIDA64_Reader_SerailOut
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reading AIDA64 Shared Memory and Sending to Serial");

            try
            {
                SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
                port.Open();

                while (true)
                    using (var file = MemoryMappedFile.OpenExisting("AIDA64_SensorValues"))
                    {
                        using (var readerz = file.CreateViewAccessor(0, 0))
                        {
                            var bytes = new byte[195];
                            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));

                            port.Write("<");

                            var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
                            using (var reader = XmlReader.Create(stringz, readerSettings))
                            {
                                while (reader.Read())
                                {
                                    using (var fragmentReader = reader.ReadSubtree())
                                    {
                                        if (fragmentReader.Read())
                                        {
                                            reader.ReadToFollowing("value");
                                            //port.Write("<");
                                            port.Write(reader.ReadElementContentAsString() + ",");
                                            //port.Write(">");

                                        }
                                    }
                                }
                            }
                            port.Write(">");
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
            }
            catch (Exception ee) { Console.WriteLine(ee.Message); }

            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}

推荐答案

首先,您需要在后台线程上运行邮件检查器.试试 BackgroundWorker 组件的大小.

First of all, you need to run your mail-checker on a background thread. Try the BackgroundWorker component on for size.

其次,使用 Timer 来触发温度更新,而不是让线程休眠.

Second, use a Timer to fire off your temperature updates instead of sleeping the thread.

为了结合这两个程序,我首先更改现有类以在发生重要事件时引发事件.例如,temp 将每 1 秒引发一个事件,而事件 args 将包含数据.

To combine the two programs, I'd start by changing the existing classes to raise events when something important happens. For example, temp will raise an event every 1 second, and the event args will contain the data.

另一方面,邮件检查器只有在完成邮件检查后才会引发事件;也许只有当未读消息的数量与上次检查相比发生变化时.

The mail checker on the other hand, will only raise an event when it has finished checking for mail; perhaps only when the number of unread messages has changed from the last check.

最后,创建一个新类,该类订阅来自每个现有程序的事件,并在触发事件时写入串行端口.此类可以将上次报告的未读消息计数存储在私有字段中,并在每次触发新事件以更新该值之前重复使用该计数.

Finally, create a new class that subscribes to the events from each of the existing programs and writes to the serial port whenever an event is fired. This class can store the last reported unread message count in a private field and reuse that every time until a new event is fired to update that value.

这篇关于如何合并两个相似但独立的程序的 C# 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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