首页 文章

从另一个类调用Timer Tick事件

提问于
浏览
0

我正在开发一个Windows窗体应用程序 . 它会在运行应用程序时触发Tick事件 . private void tmrDisplay_Tick(object sender,EventArgs e) - 当线程启动时,期望从另一个类调用方法 . 有关如何从另一个类调用相同的tick事件的任何帮助 - Class1 c?万分感谢

namespace XT_3_Sample_Application
 {
   public partial class Form1 : Form
    {
    TcpClient tcpClient;
    Socket Socket_Client;
    StreamReader TcpStreamReader_Client;    // Read in ASCII
    Queue<string> receivedDataList = new Queue<string>();



    System.Timers.Timer tmrTcpPolling = new System.Timers.Timer(); 

    public Form1()
    {
        InitializeComponent();
        TM702_G2_Connection_Initialization();



    }

    void TM702_G2_Connection_Initialization()
    {
        tmrTcpPolling.Interval = 1;
        tmrTcpPolling.Elapsed += new ElapsedEventHandler(tmrTcpPolling_Elapsed);
    }
    #region Timer Event
    void tmrTcpPolling_Elapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            if (tcpClient.Available > 0)
            {
                receivedDataList.Enqueue(TcpStreamReader_Client.ReadLine());
            }
        }
        catch (Exception)
        {

            //throw;
        }
    }

    private void tmrDisplay_Tick(object sender, EventArgs e)
    {

        if (receivedDataList.Count > 0)
        {
            string RAW_Str = receivedDataList.Dequeue();
            //tbxConsoleOutput.AppendText(RAW_Str + Environment.NewLine);
            tbxConsoleOutput.AppendText(Parser_Selection(RAW_Str) + Environment.NewLine);
        }
    } 
   #endregion

   private void btnConnect_Click(object sender, EventArgs e)
    {
        tbxConsoleOutput.AppendText(Connection_Connect(tbxTCPIP.Text, Convert.ToInt32(tbxPort.Text, 10)));
        Thread t = new Thread(threadcal);
        t.Start(); 
    }
    static void threadcal()
    {
        Class1 c = new Class1();
        c.test("192.168.2.235",9999);

      }
  }
}

1 回答

  • 2

    只要您具有对计时器类的引用,就可以公开可以调用的公共tick方法 . 然后在计时器的事件中使用它而不是复制代码

    private void tmrDisplay_Tick(object sender, EventArgs e)
    {
        Tick();
    }
    
    public void Tick()
    {
        if (receivedDataList.Count > 0)
        {
            string RAW_Str = receivedDataList.Dequeue();
            //tbxConsoleOutput.AppendText(RAW_Str + Environment.NewLine);
            tbxConsoleOutput.AppendText(Parser_Selection(RAW_Str) + Environment.NewLine);
        }
    }
    

相关问题