简体   繁体   English

在方法中更改Textbox.text; 因为返回而导致循环不循环

[英]Changing Textbox.text within a method; For loop not looping due to Return

Below is a button, when pressed it calls a function that pings a bunch of IP addresses. 下面是一个按钮,当按下它时会调用一个ping一堆IP地址的函数。 If the IP address returns a response, it adds the IP address to the output_networkSearch.Text. 如果IP地址返回响应,则将IP地址添加到output_networkSearch.Text。

private void button_networkSearch_Click(object sender, RoutedEventArgs e)
    {
        output_networkSearch.Text = networkSearch(Convert.ToInt32(input_searchLimit.Text)); 

    }

Below isn't the whole method, just the part that I can't get to work. 以下不是整个方法,只是我无法工作的部分。 The for loop starts at whatever the last digit on the users default gateway IP address is, and stops at whatever limit they have inputed (1 - 255). for循环从用户默认网关IP地址的最后一位数开始,并在它们输入的任何限制时停止(1 - 255)。

// i is equal to the last digit in the default gateway IP, if it was 192.168.0.1 then i = 1. // i等于默认网关IP中的最后一位数,如果它是192.168.0.1则i = 1。

for (int i = Convert.ToInt32(splitGatewayIP[3]); i <= searchLimit; i = i + 1)
                    {
                        // If the method receieves a ping reply...
                        if (PingHostSweep(gatewayIPRebuild + i))
                        {
                            // Returns 192.168.0. + i + ACTIVE
                            string response = gatewayIPRebuild + i + " ACTIVE";

                            return response;
                        }
                        else
                        {
                            string response = gatewayIPRebuild + i + " CLOSED";

                            return response;

                        }
                    }

This worked on a console application but for a WPF application it seems to run through the loop once and stop due to the return statement. 这适用于控制台应用程序,但对于WPF应用程序,它似乎通过循环运行一次并因return语句而停止。

My idea to work around this would be to remove the Return Response statements and try and access the TextBox (output_networkSearch) directly. 我想解决这个问题的方法是删除Return Response语句并尝试直接访问TextBox(output_networkSearch)。

So I would do something like: 所以我会这样做:

for (int i = Convert.ToInt32(splitGatewayIP[3]); i <= searchLimit; i = i + 1)
                    {
                        // If the method receieves a ping reply...
                        if (PingHostSweep(gatewayIPRebuild + i))
                        {
                            // Returns 192.168.0. + i + ACTIVE
                            string response = gatewayIPRebuild + i + " ACTIVE";

                            output_networkSearch.Text = reponse;
                        }
                        else
                        {
                            string response = gatewayIPRebuild + i + " CLOSED";

                           output_networkSearch.Text = reponse;

                        }
                    }

HOWEVER, I can't access the textbox within the method for some reason. 但是,由于某种原因,我无法访问方法中的文本框。 I've only just started learning C# so I'm not entirely familiar with how it works. 我刚刚开始学习C#,所以我并不完全熟悉它是如何工作的。

Here's an image of a partially working concept. 这是一个部分工作概念的图像。 As you can see the limit is set at 10, so it should ping IP address 1 through 10 and give an ACTIVE or CLOSED response. 如您所见,限制设置为10,因此它应该ping IP地址1到10并给出ACTIVE或CLOSED响应。 This did work in my console application version. 这在我的控制台应用程序版本中有效。

WPF version WPF版本

Console version 控制台版本

This might do the trick for you 这可能对你有所帮助

List<string> responses = new List<string>();
string response;
for (int i = Convert.ToInt32(splitGatewayIP[3]); i <= searchLimit; i = i + 1)
{
    if (PingHostSweep(gatewayIPRebuild + i))
    {
        response = gatewayIPRebuild + i + " ACTIVE";
    }
    else
    {
        response = gatewayIPRebuild + i + " CLOSED";
    }
    responses.Add(response)
}

Now after the loop the list which is responses would have the list of all the IPs which are active and closed. 现在循环之后,作为responses的列表将具有活动和关闭的所有IP的列表。 Like the way you do had in the console Application. 就像你在控制台应用程序中所拥有的那样。

i think you need use threading , there are need many child threading work in backend to scan, when they finish them work then response the result to MainForm, so i write some code hope can help you! 我认为你需要使用threading ,在后端需要很多子线程工作来扫描,当他们完成它们的工作然后将结果响应给MainForm,所以我写了一些希望可以帮助你的代码!

using System.Threading;
using System.Threading.Tasks;


        public void Start(string ip)
        {
            Task.Factory.StartNew(() =>
           {
                // If the method receieves a ping reply...
                string response;
               if (PingHostSweep(ip))
               {
                    // Returns 192.168.0. + i + ACTIVE
                    response = ip + " ACTIVE";
               }
               else
               {
                   response = ip + " CLOSED";
               }
               this.Invoke((MethodInvoker)(() => { textBox1.AppendText("\r\n" + response); }));

           });
        }


        private void button1_Click(object sender, EventArgs e)
        {

            for (int i = 1; i <= 255; i++)
            {
                Start(String.Format("192.168.100.{0}", i));
            }
        }

The previous answer was correct (though it didn't touch on a more advanced point that you will ultimately need to learn ... delegation and invocation ... long story ... won't bore you now). 之前的答案是正确的(虽然它没有触及你最终需要学习的更高级的一点......授权和调用......长篇故事......现在不会让你烦恼)。

What you wrote distills to this: 你写的东西对此有所提炼:

// SIDE NOTE: you cannot actually treat an IPv4 address as four "pure" quads (but that's not your question) // SIDE注意:您实际上无法将IPv4地址视为四个“纯”四边形(但这不是您的问题)

var notNecessarilyAHost = splitGatewayIP[3];
var searchStart = Convert.ToInt32(notNecessarilyAHost);
for (var i = searchStart; i <= searchLimit; ++i)
{
    if (PingHostSweep(gatewayIPRebuild + i))
    {
        return $"{gatewayIPRebuild}{i} ACTIVE";
    }
    else
    {
        return $"{gatewayIPRebuild}{i} CLOSED";
    }
}

...and if you (mentally) step through what you wrote it's fairly straightforward to see that the loop will only ever cycle once. ......如果你(精神上)单步执行你写的内容,那么看到循环只会循环一次是相当简单的。 Upon entry to the loop i will be equal to whatever searchStart is. 进入循环后,我将等于searchStart。 Then you enter the if test. 然后输入if测试。 If that test is true, you fall into the true side of the branch (ie, "...ACTIVE"). 如果该测试为真,则属于分支的真实一面(即“...... ACTIVE”)。 Otherwise, you'll drop into the else branch (ie, "...CLOSED". FROM THERE... 否则,你将进入else分支(即“......已关闭”。来自那里......

You ALWAYS return. 你总是回来。 That will exit the loop (and the function that contains it). 这将退出循环(以及包含它的函数)。 You will never cycle the loop again. 你永远不会再循环循环。 "break" and "return" (and plausibly goto ... but that's for a different day) will ALWAYS exit the current scope (scope being a block of code wrapped by '{' and '}' (be they explicitly or implicitly written). “break”和“return”(并且合理地转到......但那是不同的一天)将始终退出当前范围(范围是由'{'和'}'包裹的代码块(无论是显式还是隐式写入)。

Following? 以下?

The previous answer was correct. 以前的答案是正确的。 It adjusts your code so that the loop adds the string you're composing with each iteration to a list of strings. 它会调整您的代码,以便循环将您正在编写的字符串与每次迭代一起添加到字符串列表中。 Then, when you exit the loop (because i reaches searchLimit) that list of strings will contain N many, well, strings. 然后,当你退出循环(因为我到达searchLimit)时,字符串列表将包含N个,很多,字符串。 You probably want to return or continue working that. 您可能想要返回或继续工作。

All that said, you can't (technically you can but you SHOULDN'T) do any of this inside a UI thread. 所有这一切,你不能(技术上你可以,但你不应该)在UI线程内做任何这些。 If you do, the UI will block (and become 100% unresponsive to the user) while the loop runs (and the network calls that it makes run), etc. 如果这样做,UI将在循环运行时阻塞(并且对用户变得100%无响应)(并且网络调用它运行),等等。

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

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