假设我有一个包含多个标签的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。
答案 0 :(得分: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
定义为DoWork 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;
}