简体   繁体   English

获取C#BackgroundWorker进程以调用Ping

[英]Getting the C# BackgroundWorker process to invoke Pings

Read through most (all?) of the answered questions regarding the C# BackgroundWorker but none seemed to apply to this situation. 阅读有关C#BackgroundWorker的大多数(全部?)已回答问题,但似乎没有一个适用于这种情况。 If I missed one, please point me in that direction! 如果我错过了,请指出我的方向!

Anyway, I having troubles getting the Ping process to run as a background process. 无论如何,我在让Ping进程作为后台进程运行时遇到麻烦。 I made a simple form application to send pings and report back. 我制作了一个简单的表单应用程序以发送ping并报告。 That worked fine but it would only results results to the user after the pings were complete -- thus the need to a background process. 效果很好,但只有在ping操作完成后才能为用户提供结果-因此需要后台处理。 I am somewhat new to C# and was unfamiliar with the particulars of BackgroundWorker. 我是C#的新手,并不熟悉BackgroundWorker的细节。 However found a helpful walkthrough from Microsoft here: http://msdn.microsoft.com/en-us/library/ywkkz4s1.aspx 但是,在此处找到了Microsoft的有用演练: http : //msdn.microsoft.com/zh-cn/library/ywkkz4s1.aspx

I am now attempting to get the same process to apply to a System.Net.NetworkInformation object instead of a System.IO.StreamReader object. 我现在正在尝试将相同的过程应用于System.Net.NetworkInformation对象,而不是System.IO.StreamReader对象。 I think I am really close (read: I can get the app to build and run) but I consistently get an error at runtime (see below). 我想我真的很接近(阅读:我可以让应用程序构建和运行),但是我在运行时始终遇到错误(请参见下文)。

This is the Microsoft code for their sample app. 这是其示例应用程序的Microsoft代码。 It works like a champ: 它像冠军一样工作:

The method in MainForm.cs that calls the Words.cs class referenced in the walkthrough MainForm.cs中的方法,该方法调用演练中引用的Words.cs类

void backgroundWorker1DoWork(object sender, DoWorkEventArgs e)
    {
        System.ComponentModel.BackgroundWorker worker;
        worker = (System.ComponentModel.BackgroundWorker)sender;
        Words WC = (Words)e.Argument;
        WC.CountWords(worker, e);
    }

The relevant method in the 'Words.cs' class 'Words.cs'类中的相关方法

   public void CountWords(
        System.ComponentModel.BackgroundWorker worker,
        System.ComponentModel.DoWorkEventArgs e)
    {
        // Initialize the variables.
        CurrentState state = new CurrentState();
        string line = "";
        int elapsedTime = 20;
        DateTime lastReportDateTime = DateTime.Now;

        if (CompareString == null ||
            CompareString == System.String.Empty)
        {
            throw new Exception("CompareString not specified.");
        }
        // Open a new stream.        
        using (System.IO.StreamReader myStream = new System.IO.StreamReader(SourceFile))
        {
            // Process lines while there are lines remaining in the file. 
            while (!myStream.EndOfStream)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    line = myStream.ReadLine();
                    WordCount += CountInString(line, CompareString);
                    LinesCounted += 1;

                    // Raise an event so the form can monitor progress. 
                    int compare = DateTime.Compare(
                        DateTime.Now, lastReportDateTime.AddMilliseconds(elapsedTime));
                    if (compare > 0)
                    {
                        state.LinesCounted = LinesCounted;
                        state.WordsMatched = WordCount;
                        worker.ReportProgress(0, state);
                        lastReportDateTime = DateTime.Now;
                    }
                }
                // Uncomment for testing. 
                System.Threading.Thread.Sleep(5);
            }

            // Report the final count values.
            state.LinesCounted = LinesCounted;
            state.WordsMatched = WordCount;
            worker.ReportProgress(0, state);
        }
    }

When I try a similar process (sending a Ping instead of a reading a file) I get this error: 当我尝试类似的过程(发送Ping而不是读取文件)时,出现此错误:

Error: Object reference not set to an instance of an object.
Details: System.Collections.ListDictionaryInternal //This is defined in the MyApp namespace as: using System.Collections
Source: MyApp
StackTrack:    at MyApp.MainForm.Bw01DoWork(Object sender, DoWorkEventArgs e) in
[path]\MainForm.cs:line 152
   at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
Target: Void Bw01DoWork(System.Object, System.ComponentModel.DoWorkEventArgs)

Here is my method. 这是我的方法。 Line 152 referenced in the error is the very last line of the last method in MainForm.cs (the var names are different, but you get the idea): 错误中引用的第152行是MainForm.cs中最后一个方法的最后一行(变量名称不同,但您可以理解):

void Bw01DoWork(object sender, DoWorkEventArgs e)
    {
        System.ComponentModel.BackgroundWorker worker;
        worker = (System.ComponentModel.BackgroundWorker)sender;
        PTResults PR = (PTResults)e.Argument;
        PR.SendPings(worker, e);  // Line 152
    }

And the relevant portion of the PTResults.cs class: 以及PTResults.cs类的相关部分:

using (Ping newPing = new Ping())
        {
            PingReply reply = newPing.Send([Target Site],[Timeout]);
            if(reply.Status == IPStatus.Success)
            {
                state.PingOK = true;
            }
            else if(reply.Status == IPStatus.TimedOut)
            {
                state.PingOK = false;
                state.PingUpdateState = " Timed Out";                   
            }
            else if(reply.Status != IPStatus.Success)
            {
                state.PingOK = false;
                state.PingUpdateState = " FAILED";                          
            }
            else
            {
                state.PingOK = false;
                state.PingUpdateState = " UNKNOWN";                     
            }
            worker.ReportProgress(0, state.PingOK);
        }

I am thinking the System.Net.NetworkInformation.Ping component cannot be invoked the same way System.IO.StreamReader is. 我在想System.Net.NetworkInformation.Ping组件不能像System.IO.StreamReader一样被调用。 Thoughts? 思考?

I doubt it makes a difference but FWIW I am coding in SharpDevelop on a Windows 8.1 system. 我怀疑这会有所不同,但是FWIW是我在Windows 8.1系统上的SharpDevelop中进行编码的。

Take a look at the Ping SendAsync, you may be able to eliminate most of your code - just call PingAsync, and handle the result being sure to dispatch it to the UI thread and then re-queue another call. 看一下Ping SendAsync,您可以消除大部分代码-只需调用PingAsync,然后处理结果,确保将其分派到UI线程,然后重新排队另一个调用。

http://msdn.microsoft.com/en-us/library/ms144961(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/ms144961(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM