static string IP_Address = "";
getIPAddress();
MessageBox.Show(IP_Address);
我的功能是这样的:
public static void getIPAddress()
{
Uri uri = new Uri("http://whatismyip.org", UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
var res = e.Result;
IP_Address = res;
};
client.DownloadStringAsync(uri);
}
我正在使用此代码设置客户端的IP地址。但问题是,当我运行代码时,首先显示的是空字符串IP_Address,然后只显示
client.DownloadStringCompleted += (s, e) =>
{
var res = e.Result;
IP_Address = res;
};
部分被执行。在显示IP_Address之前运行上述代码块的任何建议。
答案 0 :(得分:1)
getIPAddress((ip) =>
{
MessageBox.Show(ip);
});
public static void getIPAddress(Action<string> callback)
{
Uri uri = new Uri("http://whatismyip.org", UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
var res = e.Result;
callback(res);
};
client.DownloadStringAsync(uri);
}