0

假设我有一个带有多个标签的 GroupBox。在这些标签中,显示了各种与 IP 相关的信息。一个信息是机器的外部 IP 地址。

string externalIP = "";

try
{
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    request.Timeout = 3000;
    System.Threading.Tasks.Task<System.Net.WebResponse> response =  request.GetResponseAsync();

    using (StreamReader stream = new StreamReader(response.Result.GetResponseStream()))
    {
        if (response.Result.ContentLength != -1)
        {
             externalIP = stream.ReadToEnd();
        }
    }               
}
catch (Exception e)
{
    externalIP = "Error.";
}

if (externalIP == "")
{
    return "No service.";
}
else
{
    return externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
}

从以下代码调用此方法:

private void updateNetworkIP()
{ 
    string ip4e = "External IPv4: " + getExternalIPv4();
    lblIP4external.Text = ip4e;

    //Get some more info here.
}

即使尚未完成,如何在 getExternalIPv4() 之后执行代码?像我上面那样设置 TimeOut 时它可以工作,但有时请求只需要更​​长的时间,但仍然可以成功完成。所以我希望仍然能够显示外部 IP,但继续执行其他方法来刷新 GroupBox。

4

1 回答 1

1

BackgroundWorker提供您所追求的。示例代码:

BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(getExternalIPv4Back);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(writeLabel);
bg.RunWorkerAsync();
//The code below this point will be executed while the BackgroundWorker does its work

您必须定义getExternalIPv4Back为 aDoWork Event Method并在其中包含要并行执行的代码;也writeLabel作为一个RunWorkerCompleted Event(需要在不引起多线程相关错误的情况下编辑标签)。那是:

private void getExternalIPv4Back(object sender, DoWorkEventArgs e)
{
    IP = "External IPv4: " + getExternalIPv4(); //IP -> Globally defined variable
}

private void writeLabel(object sender, RunWorkerCompletedEventArgs e)
{
   lblIP4external.Text = IP;
}
于 2013-08-17T11:50:52.417 回答