0

所以我正在尝试从 snmpsharpnet 创建一个使用 SNMP 的基本 WinForm 应用程序。

我有两个按钮“Eye”和“Jitter”,当按下一个按钮时,一个计时器启动,它每分钟在计时器处理程序内执行 SNMP 代码。

我正在尝试将 SNMP 输出从计时器处理程序写入文本框,但是当我退出程序时,我尝试的所有操作都会导致线程异常或持续运行的进程。

我已经尝试了很多不同的方法来修复这两个错误,我可能把一切都搞砸了,但这是我拥有的代码:

using System;
using System.Net;
using SnmpSharpNet;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public static bool stop = false; 
        static bool min = false, sec = false, eye = false, jitter = false;
        static string ipAdd = "";
        static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        static int alarmCounter = 1;
        static bool exitFlag = false;
        static TextBox textbox;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textbox = outputBox;
        }

        private void IPtext_TextChanged(object sender, EventArgs e)
        {
            ipAdd = IPtext.Text;
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            stop = true;
            timer.Stop();
        }

        // This is the method to run when the timer is raised.
        private static void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs)
        {
            timer.Stop();

            // If stop button has not been pressed then continue timer.
            if (stop == false)
            {
                textbox.Clear();
                // Restarts the timer and increments the counter.
                alarmCounter += 1;
                timer.Enabled = true;
                /*
                textbox.Invoke(
                    new MethodInvoker(
                        delegate { textbox.AppendText("fsjdaò"); }));
                */
                System.IO.StreamWriter file;
                if (eye == true)
                {
                    file = new System.IO.StreamWriter("c:/Users/bshellnut/Desktop/Eye.txt", true);
                }
                else
                {
                    file = new System.IO.StreamWriter("c:/Users/bshellnut/Desktop/Jitter.txt", true);
                }

                // SNMP community name
                OctetString community = new OctetString("public");

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
                param.Version = SnmpVersion.Ver2;
                // Construct the agent address object
                // IpAddress class is easy to use here because
                //  it will try to resolve constructor parameter if it doesn't
                //  parse to an IP address
                IpAddress agent = new IpAddress(ipAdd);

                // Construct target
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                // Define Oid that is the root of the MIB
                //  tree you wish to retrieve
                Oid rootOid;
                if (eye == true)
                {
                    rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.14"); // ifDescr
                }
                else
                {
                    rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.15");
                }

                // This Oid represents last Oid returned by
                //  the SNMP agent
                Oid lastOid = (Oid)rootOid.Clone();

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.GetBulk);

                // In this example, set NonRepeaters value to 0
                pdu.NonRepeaters = 0;
                // MaxRepetitions tells the agent how many Oid/Value pairs to return
                // in the response.
                pdu.MaxRepetitions = 5;

                // Loop through results
                while (lastOid != null)
                {
                    // When Pdu class is first constructed, RequestId is set to 0
                    // and during encoding id will be set to the random value
                    // for subsequent requests, id will be set to a value that
                    // needs to be incremented to have unique request ids for each
                    // packet
                    if (pdu.RequestId != 0)
                    {
                        pdu.RequestId += 1;
                    }
                    // Clear Oids from the Pdu class.
                    pdu.VbList.Clear();
                    // Initialize request PDU with the last retrieved Oid
                    pdu.VbList.Add(lastOid);
                    // Make SNMP request
                    SnmpV2Packet result;
                    try
                    {
                        result = (SnmpV2Packet)target.Request(pdu, param);
                        //textbox.Text = "";
                    }
                    catch (SnmpSharpNet.SnmpException)
                    {
                        textbox.Invoke(
                            new MethodInvoker(
                                delegate { textbox.AppendText("Could not connect to the IP Provided."); }));
                        timer.Stop();
                        //outputBox.Text += "Could not connect to the IP Provided.";
                        break;
                    }
                    // You should catch exceptions in the Request if using in real application.

                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by 
                        // the Agent - see SnmpConstants for error definitions
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            /*Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                result.Pdu.ErrorStatus,
                                result.Pdu.ErrorIndex);*/
                                textbox.Invoke(
                                    new MethodInvoker(
                                        delegate { textbox.AppendText("Error in SNMP reply. " + "Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex); }));
                            //outputBox.Text = "Error in SNMP reply. " + "Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                            lastOid = null;
                            break;
                        }
                        else
                        {
                            // Walk through returned variable bindings
                            foreach (Vb v in result.Pdu.VbList)
                            {
                                // Check that retrieved Oid is "child" of the root OID
                                if (rootOid.IsRootOf(v.Oid))
                                {
                                    /*Console.WriteLine("{0} ({1}): {2}",
                                        v.Oid.ToString(),
                                        SnmpConstants.GetTypeName(v.Value.Type),
                                        v.Value.ToString());*/

                        textbox.Invoke(
                                            new MethodInvoker(
                                                 delegate { textbox.AppendText(v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
                                            " " + v.Value.ToString() + Environment.NewLine); }));

                                    //outputBox.Text += v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
                                       //" " + v.Value.ToString() + Environment.NewLine;

                    file.WriteLine(v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
                                   " " + v.Value.ToString(), true);
                                    if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                        lastOid = null;
                                    else
                                        lastOid = v.Oid;
                                }
                                else
                                {
                                    // we have reached the end of the requested
                                    // MIB tree. Set lastOid to null and exit loop
                                    lastOid = null;
                                }
                            }
                        }
                    }
                    else
                    {
                        //Console.WriteLine("No response received from SNMP agent.");
                        textbox.Invoke(
                            new MethodInvoker(
                                delegate { textbox.AppendText("No response received from SNMP agent."); }));
                        //outputBox.Text = "No response received from SNMP agent.";
                    }
                }
                target.Close();
                file.Close();
            }
            else
            {
                // Stops the timer.
                exitFlag = true;
            }
        }

        private void eyeButton_Click(object sender, EventArgs e)
        {
            outputBox.Text = "Connecting...";
            eye = true;
            jitter = false;
            stop = false;

            timer.Tick += new EventHandler(TimerEventProcessor);

            // Sets the timer interval to 5 seconds.
            timer.Interval = 5000;
            timer.Start();

            // Runs the timer, and raises the event.
            while (exitFlag == false)
            {
                // Processes all the events in the queue.
                Application.DoEvents();
            }
        }

        private void jitterButton_Click(object sender, EventArgs e)
        {
            outputBox.Text = "Connecting...";
            eye = false;
            jitter = true;
            stop = false;

            timer.Tick += new EventHandler(TimerEventProcessor);

            // Sets the timer interval to 5 seconds.
            timer.Interval = 5000;
            timer.Start();

            // Runs the timer, and raises the event.
            while (exitFlag == false)
            {
                // Processes all the events in the queue.
                Application.DoEvents();
            }
        }

        private void Seconds_CheckedChanged(object sender, EventArgs e)
        {
            min = false;
            sec = true;
        }

        private void Minutes_CheckedChanged(object sender, EventArgs e)
        {
            min = true;
            sec = false;
        }
    }
}
4

2 回答 2

1

我相信您在 UI 线程上遇到了死锁。

TimerEventProcessor()由您的 实例调用System.Windows.Forms.Timer,该实例在 UI 线程上运行。当计时器关闭时,我相信它会将一条消息放入 UI 线程的消息队列中以调用您的TimerEventProcessor()方法。该方法依次调用textbox.Invoke(),将另一条消息放入队列,然后等待它被处理

您的 UI 线程现在卡住了,因为它正在处理一条消息,但必须等到另一条消息被处理后才能继续。Application.DoEvents()对你没有好处的调用,因为一旦你的程序进入它们就不会被调用TimerEventProcessor()。(它们也是不必要的,因为您的按钮单击处理程序无论如何都不会阻塞 UI 线程。)

由于计时器在 UI 线程上运行,因此您可以摆脱textbox.Invoke()调用而直接访问textbox

概括:

  1. 将您的呼叫替换为textbox.Invoke()直接访问textbox
  2. 删除您的来电Application.DoEvents()

注意:如果您从MSDN 示例Application.DoEvents()中获得了使用计时器的逻辑,他们会将其放在那里,以便在 Main 函数完成后应用程序不会退出。

更新:textbox.Invoke您可以通过将调用替换为以下代码来查看这是否真的是问题所在。如果此代码有效,那么您肯定遇到了 UI 消息队列死锁问题。此外,如果这确实解决了问题,我不建议将其作为解决方案,而是按照上面的建议解决死锁。

// Make the request asynchronously
System.IAsyncResult asyncResult = textbox.BeginInvoke(
    new MethodInvoker(
        delegate { /* insert delegate code here */ }));

// Process the message queue until this request has been completed
while(!asyncResult.IsCompleted) Application.DoEvents();

// Clean up our async request
textbox.EndInvoke(asyncResult);

由于您的代码似乎可以正常工作,因此您可以忽略上面的测试代码。

于 2012-08-06T16:15:20.090 回答
0

您的问题与计时器无关,Invoke您使用的所有语句都不是必需的。该类System.Windows.Forms.Timer在 UI 线程中运行。看这里:http: //msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

于 2012-08-06T16:09:42.633 回答