2013-08-17 60 views
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的其他方法。

回答

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; 
} 
相關問題